問題描述
Laravel 模型允許使用兩個函數(shù)將值插入到數(shù)據(jù)庫表中.他們是
Laravel Model allows two functions for inserting the values to the database table. They are
創(chuàng)建:User::create(['id'=>1,'name'=>'stack']);
插入:User::insert(['id'=>2,'name'=>'overflow']);
我發(fā)現(xiàn)它們執(zhí)行類似的操作.它們有什么區(qū)別?
I found they perform similar operations. What's difference between them?
推薦答案
insert() :
如果你使用 insert() 方法,你不能默認 created_at 和 updated_at 數(shù)據(jù)庫列它將為空
If you using insert() method you can't default created_at and updated_at database column it will be null
DefaultUser::insert(['username' => $request->username, 'city' => $request->city, 'profile_image' => $request->profile_image]);
<小時>
create() :當我們使用 create 方法時,您必須在 fillable fields
create() : when we use create method you must define this model in fillable fields
添加模型
protected $fillable = ['username','city', 'profile_image'];
添加控制器
DefaultUser::create(['username' => $request->username, 'city' => $request->city, 'profile_image' => $request->profile_image]);
那么我們就可以使用create方法而沒有**mass assignment error **基本上在這里,表定義的字段在您的模型中受到保護
then we can use create method without **mass assignment error ** basically here , table defined fields are protected in your model
您應該定義要使質量可分配的模型屬性.您可以使用模型上的 $fillable 屬性來執(zhí)行此操作
這篇關于Laravel 模型函數(shù)“create"和“create"有什么區(qū)別?和“插入"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!