我有一个函数,它使用查询生成器向数据库插入记录。我想手动使用事务。
但是,记录被插入到数据库,而不调用commit()函数。我不知道为什么;我想要插入函数等待我,直到我调用commit()函数。
在我的脚本中有两个命令:
将command)
products (将插入product_categories (无效命令)-我设置了字段prd_idd,而不是prd_id)在这种情况下,当#2失败时,我希望命令#1不要插入数据库。
public function create($params)
{
DB::beginTransaction();
try {
DB::table('products')->insert($params);
DB::table('prd_categories')->insert(['prd_idd'=> 1, 'category_id' => 1]);
} catch (\Exception $ex) {
echo $ex->getMessage();
DB::rollback();
}
die("End");
}发布于 2020-06-10 04:46:18
要在数据库transaction中运行一组操作,可以在DB外观上使用事务方法。如果在事务Closure中抛出异常,事务将自动回滚。如果Closure成功执行,事务将自动提交。在使用transaction方法时,不需要担心手动回滚或提交:
DB::transaction(function () {
DB::table('product')->insert(...);
DB::table('prd_categories')->insert(...);
});https://stackoverflow.com/questions/62295825
复制相似问题