本文介紹了Laravel Eloquent - 附加與同步的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
Laravel 4 的 Eloquent ORM 中的 attach()
和 sync()
有什么區(qū)別?我試圖環(huán)顧四周,但找不到任何東西!
解決方案
attach():
- 在處理多對多關(guān)系時(shí)插入相關(guān)模型
- 不需要數(shù)組參數(shù)
示例:
$user = User::find(1);$user->roles()->attach(1);
sync():
與attach()
方法類似,sync()
方法用于附加相關(guān)模型.但是,主要區(qū)別在于:
sync()
接受要放在數(shù)據(jù)透視表上的 ID 數(shù)組- 其次,最重要的,如果數(shù)組中不存在模型,同步方法會從數(shù)據(jù)透視表中刪除數(shù)據(jù),并只將新項(xiàng)目插入數(shù)據(jù)透視表.
示例:
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
這篇關(guān)于Laravel Eloquent - 附加與同步的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!