我已经在Google上搜索了几天,但找不到解决方案。我想知道laravel应用程序如何打开与mysql数据库的连接。
案例1:
//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
案例2:
//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();
案例3:
\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?
感谢您的帮助。
答案 0 :(得分:1)
这是我的答案
案例1:
两个查询都将使用相同的连接。 Laravel对一个请求使用一个连接(您也可以创建多个连接,但默认情况下,它始终使用一个连接)
案例2:
您将在此处手动提交更改,这意味着您正在事务内部创建检查点。提交的更改无法回滚。在这种情况下,Laravel也使用它在启动时创建的相同连接。
案例3:
所有三个插入将被回滚
注意:DB::beginTransaction()
必须具有DB::endTransaction()
才能关闭交易。
注意:数据库事务也像普通插入或选择查询一样查询。在上述所有情况下,Laravel只是准备查询并将其使用其连接发送到数据库。