Reputation: 205
I have been searching on google several days but can't find the solution. I wonder how laravel application open connection with mysql database.
Case1:
//open db connection
\DB::table('test')->insert(['name' => Str::random(15)]);
//does laravel close connection after done and open a new one when have new query?
\DB::table('test')->insert(['name' => Str::random(15)]);
//close connection
Case2:
//What will happen if we use \DB transaction (compare with case1)
\DB::beginTransaction();
\DB::table('test')->insert(['name' => Str::random(15)]);
\DB::table('test')->insert(['name' => Str::random(15)]);
\DB::commit();
Case3:
\DB::beginTransaction();
\DB::table('test')->insert(['name' => Str::random(15)]);
\DB::table('test')->insert(['name' => Str::random(15)]);
\DB::table('test')->insert(['name' => Str::random(15)]);
\DB::rollback();
//3 query statements will be rollback? So do anything happen with the database or nothing?
Thanks for any help.
Upvotes: 1
Views: 940
Reputation: 6722
Here is my answer
Case1:
Both the queries will be using the same connection. Laravel uses one connection for one request (You can create multiple as well but by default it always uses one)
Case2:
You are manually committing the changes here which means you are creating check points inside a transaction. The committed changes cannot be rolled back. In this case also Laravel uses same connection which it created on boot.
Case3:
All three inserts will be rolled back
NOTE: DB::beginTransaction()
has to have DB::endTransaction()
to close the transaction.
NOTE: DB transactions are also queries like normal insert or select queries. In all the above cases, Laravel is just preparing the query and sending it to the Database using the connection it has.
Upvotes: 1