When the laravel framework MySQL connects multiple libraries, the transaction processing needs to specify the library

Time:2021-3-30

Such as the title

In fact, this is not the reason for the laravel framework. Java programs have been found on the Internet. You need to specify a library to process things using MySQL multiple libraries.

Several libraries are used in laravel framework project to store business sub libraries, and the connected libraries are specified in model.

protected $connection = 'mysql_bms';

Using transactions in code

DB::beginTransaction();
try{
    ....
    DB::commit();
}
catch (Exception $e){
    DB::rollback();
}

Today’s test found that the transaction did not work.

After studying for a long time, we found that it was the reason for connecting multiple databases. Transaction processing needs to write as follows:

DB::connection('mysql_bms')->beginTransaction();
try{
    ....
    DB::connection('mysql_bms')->commit();
}
catch (Exception $e){
    DB::connection('mysql_bms')->rollback();
}

In the program, only the table of a single library is used, so it is OK to specify the connectionTables with mixed use of multiple librariesWhat about it?

The solution of Java program found on the Internet should also be suitable for PHP, that isThe tables used by the program are connected to multiple libraries, and each of them has to be transacted

DB:: connection ('library 1 ') - > begintransaction();
DB:: connection ('library 2 ') - > begintransaction();
try{
    ....
    DB:: connection ('library 1 ') - > commit();
    DB:: connection ('library 2 ') - > commit();
}
catch (Exception $e){
    DB:: connection ('library 1 ') - > rollback();
    DB:: connection ('library 2 ') - > rollback();
}

No practical application, have the opportunity to test in the work.