Laravel 8 新增方法

2021-07-19 11:41 更新

除了 savesaveMany 方法外,你還可以使用 create 方法。它接受一個屬性數組,同時會創(chuàng)建模型并插入到數據庫中。 還有, save 方法和 create 方法的不同之處在于, save 方法接受一個完整的 Eloquent 模型實例,而 create 則接受普通的 PHP 數組:

$post = App\Models\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]); 

技巧:在使用 create 方法前,請務必確保查看過本文檔的 批量賦值 章節(jié)。

你還可以使用 createMany 方法去創(chuàng)建多個關聯模型:

$post = App\Models\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

你還可以使用 findOrNew、firstOrNew、firstOrCreateupdateOrCreate 方法來 創(chuàng)建和更新關系模型。


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號