Laravel Model函数之间的“创建"区别是什么?和“插入"? [英] What's difference between Laravel Model functions "create" and "insert"?
问题描述
Laravel模型允许使用两个函数将值插入数据库表.他们是
Laravel Model allows two functions for inserting the values to the database table. They are
创建:
User::create(['id'=>1,'name'=>'stack']);
插入:
User::insert(['id'=>2,'name'=>'overflow']);
我发现他们执行类似的操作.他们之间有什么区别?
I found they perform similar operations. What's difference between them?
推荐答案
insert():
如果使用insert()方法,则无法默认使用created_at和Updated_at数据库列 将为空
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() : 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分配错误** 基本上在这里,表定义的字段在您的模型中受到保护
then we can use create method without **mass assignment error ** basically here , table defined fields are protected in your model
,您应该定义要批量分配的模型属性.您可以使用模型上的$ fillable属性来完成此操作
这篇关于Laravel Model函数之间的“创建"区别是什么?和“插入"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!