Laravel Eloquent - 附加与同步
本文介绍了Laravel Eloquent - 附加与同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Laravel 4 的 Eloquent ORM 中的 attach()
和 sync()
有什么区别?我试图环顾四周,但找不到任何东西!
解决方案
attach():
- 在处理多对多关系时插入相关模型
- 不需要数组参数
示例:
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():
- Insert related models when working with many-to-many relations
- No array parameter is expected
Example:
sync():
Similar to the attach()
method, the sync()
method is used to attach related models. However, the main differences are:
sync()
accepts an array of IDs to place on the pivot table- Secondly, most important, the sync method will delete the data from the pivot table if the model does not exist in the array, and insert only the new items to the pivot table.
Example:
user_role
id user_id role_id 1 12 1 2 12 5 3 12 2
The above operation will delete:
id user_id role_id 2 12 5
And insert role_id 3
to the table.
user_role table
id user_id role_id 1 12 1 3 12 2 4 12 3
这篇关于Laravel Eloquent - 附加与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!