9
我需要知道的是什麼樣的save()
和laravel 5 區別create()
函數,這個函數可以使用save()
和create()
()函數?什麼保存之間是不同的(),創建於laravel 5
我需要知道的是什麼樣的save()
和laravel 5 區別create()
函數,這個函數可以使用save()
和create()
()函數?什麼保存之間是不同的(),創建於laravel 5
Model::create
是圍繞$model = new MyModel(); $model->save()
的簡單包裝,請參見實現
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return static
*/
public static function create(array $attributes = [])
{
$model = new static($attributes);
$model->save();
return $model;
}
保存()
save()方法既用於節能新模式,並更新 現有的。在這裏您正在創建新模型或找到現有模型, 逐個設置其屬性,最後保存在數據庫中。
節省()接受全鋒模型實例
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);`
$post->comments()->save($comment);
創建()
創建()接受純 PHP數組
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
EDIT
作爲@PawelMysior指出的那樣,使用create方法之前,一定要 標記,其值是安全的一組列通過批量賦值(例如name,birth_date等),我們需要通過提供一個名爲$ fillable的新屬性來更新我們的Eloquent模型。這簡直是包含安全通過質量分配,設置屬性的名稱數組: 例如: -
類國家擴展模式{
protected $fillable = [
'name',
'area',
'language',
];
}
感謝您回覆,但你能否給我更詳細的闡述。我閱讀了Laravel文檔,但從那裏我沒有多少想法。 –
感謝您的詳細描述。 –
需要注意的一點是:如果您打算使用create(),那麼您傳遞給它的所有屬性都必須列在模型的$ fillable屬性中。見:https://laravel.com/docs/master/eloquent#mass-assignment – PawelMysior