Laravel雄辩 - 连接vs同步 [英] Laravel Eloquent - Attach vs Sync

查看:122
本文介绍了Laravel雄辩 - 连接vs同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

推荐答案

attach():


  • 在处理多对多关系时插入相关模型

  • 不需要数组参数

示例:


$user = User::find(1);

$user->roles()->attach(1);

sync()

attach()方法。 sync()也用于附加相关模型。但主要的区别是:

Similar to the attach() method. sync() also use to attach related models. However main difference is:


  • 同步方法接受一组ID放在数据透视表上

  • 其次,最重要的,如果模型不存在于数组中并将新项目插入到数据透视表中,则sync方法将从表中删除模型。

  • Sync method accepts an array of IDs to place on the pivot table
  • Secondly, most important, The sync method will delete the models from table if model does not exist in array and insert new items to the pivot table.

示例:

user_role


id  user_id role_id
1    2       1
2    2       5
3    2       2




$user->roles()->sync(array(1, 2, 3));

上述操作将删除:


id  user_id role_id
2    2       5

并插入 role_id 3 到表格。

user_role表


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

这篇关于Laravel雄辩 - 连接vs同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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