Laravel 4 的 Eloquent ORM 中的 attach()
和 sync()
有什么区别?我试图环顾四周,但找不到任何东西!
attach():
示例:
$user = User::find(1);$user->roles()->attach(1);
sync():
与attach()
方法类似,sync()
方法用于附加相关模型.但是,主要区别在于:
sync()
接受要放在数据透视表上的 ID 数组示例:
user_role
<前>id user_id role_id1 12 12 12 53 12 2$user = User::find(12);$user->roles()->sync(array(1, 2, 3));
以上操作将删除:
<前>id user_id role_id2 12 5然后将 role_id 3
插入到表中.
user_role 表
<前>id user_id role_id1 12 13 12 24 12 3What 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():
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:
sync()
accepts an array of IDs to place on the pivot tableExample:
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 3
to the table.
user_role table
id user_id role_id 1 12 1 3 12 2 4 12 3
这篇关于Laravel Eloquent - 附加与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!