W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Eloquent 為新模型添加關(guān)聯(lián)提供了便捷的方法。例如,也許你需要添加一個(gè)新的 Comment
到一個(gè) Post
模型中。你不用在 Comment
中手動(dòng)設(shè)置 post_id
屬性,就可以直接使用關(guān)聯(lián)模型的 save
方法將 Comment
直接插入:
$comment = new App\Models\Comment(['message' => 'A new comment.']);
$post = App\Models\Post::find(1);
$post->comments()->save($comment);
需要注意的是,我們并沒有使用動(dòng)態(tài)屬性的方式訪問 comments
關(guān)聯(lián)。相反,我們調(diào)用 comments
方法來獲得關(guān)聯(lián)實(shí)例。save
方法將自動(dòng)添加適當(dāng)?shù)?post_id
值到 Comment
模型中。
如果你需要保存多個(gè)關(guān)聯(lián)模型,你可以使用 saveMany
方法:
$post = App\Models\Post::find(1);
$post->comments()->saveMany([
new App\Models\Comment(['message' => 'A new comment.']),
new App\Models\Comment(['message' => 'Another comment.']),
]);
save
和 saveMany
方法不會(huì)將新模型加載到父模型上。 如果你想在使用 save
或 saveMany
方法之后訪問該關(guān)聯(lián),需要使用 refresh
方法來重新加載模型及其關(guān)聯(lián):
$post->comments()->save($comment);
$post->refresh();
// 所有評(píng)論,包括新保存的評(píng)論...
$post->comments;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: