在Laravel中同步一对多关系 [英] Synchronizing a one-to-many relationship in Laravel

查看:470
本文介绍了在Laravel中同步一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多对多关系,则使用其sync方法更新关系非常容易.

If I have a many-to-many relationship it's super easy to update the relationship with its sync method.

但是我要用什么来同步一对多关系?

But what would I use to synchronize a one-to-many relationship?

  • posts:id, name
  • links:id, name, post_id
  • table posts: id, name
  • table links: id, name, post_id

在这里,每个Post可以有多个Link.

Here, each Post can have multiple Links.

我想根据输入的链接集合(例如,来自CRUD表单,可以在其中添加,删除和修改链接)来同步与数据库中特定帖子关联的链接.

I'd like to synchronize the links associated with a specific post in the database, against an inputted collection of links (for example, from a CRUD form where I can add, remove, and modify links).

应删除输入集合中不存在的数据库链接.应该更新数据库和我的输入中存在的链接以反映输入,并且应该将仅存在于我的输入中的链接添加为数据库中的新记录.

Links in the database that aren't present in my input collection should be removed. Links that exist in the database and in my input should be updated to reflect the input, and links that are only present in my input should be added as new records in the database.

总结所需的行为:

  • inputArray = true/db = false ---创建
  • inputArray = false/db = true ---删除
  • inputArray = true/db = true ---- UPDATE

推荐答案

不幸的是,没有用于一对多关系的sync方法.自己做很简单.至少如果您没有任何引用links的外键.因为这样您可以简单地删除行,然后再次插入所有行.

Unfortunately there is no sync method for one-to-many relations. It's pretty simple to do it by yourself. At least if you don't have any foreign key referencing links. Because then you can simple delete the rows and insert them all again.

$links = array(
    new Link(),
    new Link()
);

$post->links()->delete();
$post->links()->saveMany($links);

如果您确实需要更新现有的(无论出于何种原因),则需要完全按照问题中的描述进行操作.

If you really need to update existing one (for whatever reason) you need to do exactly what you described in your question.

这篇关于在Laravel中同步一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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