Laravel DB::rollback() doesn't work for transaction processes

随声附和 提交于 2020-03-23 12:37:57

问题


First off my engine is innoDB and I already tried the following on mySQL:

BEGIN;
INSERT INTO `tbl_users`(...) VALUES (...)
ROLLBACK();

And it works fine, meaning the problem wasn't in my mysql config.

But when I tried this on my Laravel Model:

public static function addNew($request, $department_id) {

    $result = array();

    $now = Carbon::now();

    DB::beginTransaction();

    //Checking for existing Order to set appropriate starting ID
    $result = DB::select("
        SELECT COUNT(`id`) AS 'count'
        FROM `tbl_consignmentorders`
    ")[0];

    if($result->count == 0){
        DB::update("ALTER TABLE `tbl_consignmentorders` AUTO_INCREMENT = 70000000001;");
    }

    try {
        //INSERT
        DB::insert("
            INSERT INTO `tbl_consignmentorders`
            (`from`, `to`, `status`, `created_at`, `updated_at`) 
            VALUES 
            (?, ?, ?, ?, ?)",
            [
                $department_id,
                strtoupper($request->input('supplier')),
                'PENDING',
                $now,
                $now
            ]
        );
        //GET THE LAST ID INSERTED, NEEDED FOR NEXT INSERT
        $last_id = DB::select("
            SELECT 
                LAST_INSERT_ID() AS 'id'
            FROM `tbl_consignmentorders`;"
        )[0]->id;

        //CONSTRUCTING QUERY STRING FOR VALUES
        $values = '';
        $count = 0;
        foreach($request->input('item_id') as $item) {
            $values .= ',(' . $request->input('quantity')[$count] . ', ' . $last_id . ', ' . $item . ', ' . $request->input('item_price_id')[$count] . ' )';
            $count++;
        }
        $values[0] = ' ';

        //INSERT TO DETAILS
        DB::insert("
            INSERT INTO `tbl_consignmentorderdetails`
            (`quantity`, `order_id`, `item_id`, `item_price_id`) 
            VALUES 
            $values;"
        );

        //INSERT TO TRANSACTION AUDIT
        DB::insert("
            INSERT INTO `tbl_transactions`
            (`type`, `reference_id`, `department_id`, `created_at`, `updated_at`) 
            VALUES 
            (?, ?, ?, ?, ?)",
            [
                'CONSIGNMENT ORDER',
                $last_id,
                $department_id,
                $now,
                $now
            ]
        );

        //COMMIT NOTHING FAILS
        DB::commit();
        $result = true;

    } catch (\Exception $e) {
        //ROLLBACK SOMETHING IS WRONG
        DB::rollback();
        $result = $e->getMessage();
    }

    return $result;
}

Now the above code works fine when successful, now to generate error, I will deliberately change this part of code:

    //GET THE LAST ID INSERTED, NEEDED FOR NEXT INSERT
    $last_id = DB::select("
        SELECT 
            LAST_INSERT_ID() AS 'id'
        FROM `tbl_consignmentorders`;"
    )[0]; //<--- I removed the ->id to return the whole object causing object to string error on the next query

Now as expected it goes to the catch block to pass the error message but, the queries executed before the error is still present in the database where it should not.


回答1:


My mistake,

I use DB::rollback(); instead of DB::rollBack(); with capital B




回答2:


If your system use multiple database configs, you need to do something like this

DB::connection('database_config_2')->beginTransaction();
DB::connection('database_config_2')->rollback();
DB::connection('database_config_2')->commit();

Hope it helps!




回答3:


The issue most people have with DB::rollBack not working is that they do not start a DB::Transaction function first!

DB::rollBack only works when a transaction has been started

A transaction can be started in two ways:

  1. Using the DB::transaction function inside your method

    DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);
    
    DB::table('posts')->delete();
    

    });

  2. By manually starting a transaction at the beginning of a method and probably when a call to an external API fails, you call the DB::rollBack() method

    DB::beginTransaction();

    DB::rollBack();



来源:https://stackoverflow.com/questions/47524670/laravel-dbrollback-doesnt-work-for-transaction-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!