Model :: create是否进行db事务

时间:2016-11-04 14:21:26

标签: php mysql database laravel eloquent

我想出了一对一插件的代码:

$anotherPet = \App\Pet::create($data);
$anotherUser = \App\User::create($data);
$anotherPet->user()->associate($anotherUser);

$anotherPet->save();

create()是否会调用db,或者是否在save()上进行了交易?

3对1来电?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

假设您正在使用laravel,create会执行一个事务,如果您只想创建一个事务,则可以创建一个新实例并像这样填充:

$anotherPet = new \App\Pet;
$anotherPet->fill($data);
$anotherUser = \App\User::create($data); // transaction is made here; mandatory to have an id for your association

$anotherPet->user()->associate($anotherUser); // no transaction
$anotherPet->save(); // transaction is made here

这样你就有2个查询而不是3个,我没有办法在没有外键约束失败的单个查询中进行查询。

相关问题