2016-11-04 36 views
0

,我想出了这样的代码,一到一个刀片:不会型号::创建使数据库事务

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

$anotherPet->save(); 

是否create()拨打电话到DB或交易上save()制成?

3对1电话?

感谢您的善意帮助。

回答

1

假设你正在使用laravel,创建做了交易,如果你只想要一个可以做创建一个新的实例,并填写像这样:

$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,我没有办法在没有外键约束的单个查询中失败。

+0

它们是2个实例,并且涉及到外键约束,所以我想到了这种模式:( 我可以用'fill()'关联()'吗? –

+0

在这种情况下,您将不得不保存对象你想关联它之前,否则你将不会有主键。 我更新了第一个答案 –