W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
您常常會需要加入新的關(guān)聯(lián)模型。例如新增一個 comment 到 post 。除了手動設(shè)定模型的 post_id 外鍵,也可以從上層的 Post 模型新增關(guān)聯(lián)的 comment :
$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$comment = $post->comments()->save($comment);
上面的例子里,新增的 comment 模型中 post_id 字段會被自動設(shè)定。
如果想要同時新增很多關(guān)聯(lián)模型:
$comments = [
new Comment(['message' => 'A new comment.']),
new Comment(['message' => 'Another comment.']),
new Comment(['message' => 'The latest comment.'])
];
$post = Post::find(1);
$post->comments()->saveMany($comments);
要更新 belongsTo 關(guān)聯(lián)時,可以使用 associate 方法。這個方法會設(shè)定子模型的外鍵:
$account = Account::find(10);
$user->account()->associate($account);
$user->save();
您也可以新增多對多的關(guān)聯(lián)模型。讓我們繼續(xù)使用 User 和 Role 模型作為例子。我們可以使用 attach 方法簡單地把 roles 附加給一個 user:
$user = User::find(1);
$user->roles()->attach(1);
也可以傳入要存在樞紐表中的屬性數(shù)組:
$user->roles()->attach(1, ['expires' => $expires]);
當(dāng)然,有 attach 方法就會有相反的 detach 方法:
$user->roles()->detach(1);
attach 和 detach 都可以接受ID數(shù)組作為參數(shù):
$user = User::find(1);
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['attribute1' => 'value1'], 2, 3]);
您也可以使用 sync 方法附加關(guān)聯(lián)模型。 sync 方法會把根據(jù) ID 數(shù)組把關(guān)聯(lián)存到樞紐表。附加完關(guān)聯(lián)后,樞紐表里的模型只會關(guān)聯(lián)到 ID 數(shù)組里的 id :
$user->roles()->sync([1, 2, 3]);
也可以在把每個 ID 加入樞紐表時,加入其他字段的數(shù)據(jù):
$user->roles()->sync([1 => ['expires' => true]]);
有時您可能想要使用一個命令,在建立新模型數(shù)據(jù)的同時附加關(guān)聯(lián)??梢允褂?save 方法達(dá)成目的:
$role = new Role(['name' => 'Editor']);
User::find(1)->roles()->save($role);
上面的例子里,新的 Role 模型對象會在儲存的同時關(guān)聯(lián)到 user 模型。也可以傳入屬性數(shù)組把數(shù)據(jù)加到關(guān)聯(lián)數(shù)據(jù)庫表:
User::find(1)->roles()->save($role, ['expires' => $expires]);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: