沃梦达 / 编程问答 / php问题 / 正文

防止 Laravel 向数据透视表添加多条记录

Preventing Laravel adding multiple records to a pivot table(防止 Laravel 向数据透视表添加多条记录)

本文介绍了防止 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);
}

或者/并且您可以在数据库中添加唯一性条件,它会在尝试保存双峰时抛出异常.

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 向数据透视表添加多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:防止 Laravel 向数据透视表添加多条记录

基础教程推荐