防止Laravel将多个记录添加到数据透视表中 [英] Preventing Laravel adding multiple records to a pivot table

查看:119
本文介绍了防止Laravel将多个记录添加到数据透视表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多对多的关系设置和工作,添加一个项目到我使用的购物车:

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);
}

或者你可以在数据库中添加unicity条件,它会抛出尝试保存双精度的例外。

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将多个记录添加到数据透视表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆