問題描述
我建立了一個多對多的關系并且正在工作,將一個項目添加到我使用的購物車中:
I have a many to many relationship set up and working, to add an item to the cart I use:
$cart->items()->attach($item);
將項目添加到數據透視表(應該如此),但如果用戶再次單擊鏈接以添加他們已經添加的項目,則會在數據透視表中創建重復條目.
Which adds an item to the pivot table (as it should), but if the user clicks on the link again to add an item they have already added it creates a duplicate entry in the pivot table.
是否有一種內置的方法可以在數據透視表不存在的情況下將記錄添加到數據透視表中?
Is there a built in way to add a record to a pivot table only if one does not already exist?
如果沒有,我如何檢查數據透視表以查找是否已存在匹配的記錄?
If not, how can I check the pivot table to find if a matching record already exists?
推薦答案
您可以通過編寫一個非常簡單的條件來檢查現有記錄的存在,如下所示:
You can check the presence of an existing record by writing a very simple condition like this one :
if (! $cart->items->contains($newItem->id)) {
$cart->items()->save($newItem);
}
或者/并且您可以在數據庫中添加唯一性條件,它會在嘗試保存雙峰時拋出異常.
Or/and you can add unicity condition in your database, it would throw an exception during an attempt of saving a doublet.
您還應該看看下面來自 Barryvdh 的更直接的回答.
You should also take a look at the more straightforward answer from Barryvdh just below.
這篇關于防止 Laravel 將多條記錄添加到數據透視表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!