Laravel 8 保存方法

2021-07-19 11:41 更新

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.']),
]); 

savesaveMany 方法不會(huì)將新模型加載到父模型上。 如果你想在使用 savesaveMany 方法之后訪問該關(guān)聯(lián),需要使用 refresh 方法來重新加載模型及其關(guān)聯(lián):

$post->comments()->save($comment);

$post->refresh();

// 所有評(píng)論,包括新保存的評(píng)論...
$post->comments; 
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)