本文介紹了Laravel Eloquent - 附加與同步的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
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():
- 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:
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
$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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!