1

I'm trying out something new on my end that whenever I have a multiple query that inserts / update. I use database transaction for that matter.

$this->transaction->beginTransaction();

try {

    $trucker_user->update([
        'username'       => $request->getParam('username'),
        'first_name'     => $request->getParam('first_name'),
        'middle_name'    => $request->getParam('middle_name'),
        'last_name'      => $request->getParam('last_name'),
        'contact_number' => $request->getParam('contact_number'),
        'email'          => $request->getParam('email'),
        'status'         => ($trucker_id) ? 1 : $request->getParam('status')
    ]);

    if ($trucker_id === false) {
        $trucker_user->userTrucker()->update([
            'trucker_id' => $request->getParam('trucker_id')
        ]);
    }

    $this->transaction->commit();
} catch(\Exception $e) {
    $this->transaction->rollBack();
    throw $e;
}

So the question is, is it a good practice when I have multiple query that inserts / update I shall be using database transaction for it?

I know it's a good idea to have a transaction when something bad happens it goes rollback. But whenever I use it always in multiple queries isn't a bit kind of overkill?

1 Answer 1

3

The transaction is a tool designed for guaranteeing consistency. If the first update/insert operation should be rolled back if the second one fails, then the transaction is needed.

In your example, you update a trucker_user's fields and then, under some circumstances, you update also its id. The question you should pose to yourself is "do I want to rollback all the trucker_user updates if the id update fails?"

The answer may be yes either because you have to maintain consistency between the two actions, or because, in case the second operation fails, you have to retry it, and doing everything again is easier than finding where the process was interrupted (so that you can start back from there).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.