php Laravel Eloquent - 附加与同步

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23968415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:04:05  来源:igfitidea点击:

Laravel Eloquent - Attach vs Sync

phplaravellaravel-4eloquentrelationship

提问by Kousha

What is the difference between attach()and sync()in Laravel 4's Eloquent ORM? I've tried to look around but couldn't find anything!

Laravel 4 的 Eloquent ORMattach()sync()Laravel 4 的 Eloquent ORM 有什么区别?我试图环顾四周,但找不到任何东西!

回答by Anam

attach():

附():

  • Insert related models when working with many-to-many relations
  • No array parameter is expected
  • 处理多对多关系时插入相关模型
  • 不需要数组参数

Example:

例子:

$user = User::find(1);
$user->roles()->attach(1);

sync():

同步():

Similar to the attach()method, the sync()method is used to attach related models. However, the main differences are:

attach()方法类似,该sync()方法用于附加相关模型。但是,主要区别是:

  • sync()accepts an array of IDs to place on the pivot table
  • Secondly, most important, the sync method will delete the models from the table if the model does not exist in the array, and insert only the new items to the pivot table.
  • sync()接受要放置在数据透视表上的一组 ID
  • 其次,最重要的是,如果模型不存在于数组中,sync 方法将从表中删除模型,并仅将新项目插入到数据透视表中。

Example:

例子:

user_role

用户角色

id  user_id role_id
1    12       1
2    12       5
3    12       2
$user = User::find(12);
$user->roles()->sync(array(1, 2, 3));

The above operation will delete:

以上操作将删除:

id  user_id role_id
2    12       5

And insert role_id 3to the table.

并插入role_id 3到表中。

user_role table

用户角色表

id  user_id role_id
1    12       1
3    12       2
4    12       3

回答by Mahmoud Zalt

To make it even simpler:

为了使它更简单:

The attachfunction only adds records to the Pivot table.

attach函数仅向数据透视表添加记录。

The syncfunction replaces the current records with the new records. This is very useful for updating a model.

sync函数用新记录替换当前记录。这对于更新模型非常有用。

Example:

例子:

Assuming you have a created Post that has many Tags attached on it where the Tags ID's are [1,2,3].

假设您有一个创建的帖子,上面附加了许多标签,其中标签 ID 是[1,2,3]

And the user has the ability to update the Post and its Tags.

并且用户可以更新帖子及其标签。

The user will send you the new Tags ID's [3,4,5].

用户将向您发送新标签 ID 的 [3,4,5]。

If you use the syncfunction, the new Tags of the Post will be [3,4,5]only.

如果您使用该sync功能,帖子的新标签将仅为[3,4,5]

If you use the attachfunction, the new Tags of the Post will be [1,2,3,4,5].

如果使用该attach函数,帖子的新标签将为[1,2,3,4,5]