2016-11-04 33 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

在這種情況下,您將不得不保存對象你想關聯它之前,否則你將不會有主鍵。 我更新了第一個答案 –