更新时间:2023-12-01 23:20:22
Eloquent
模型已经封装了对象的属性.因此,您只能通过 set
($model->attribute
) 或 fill(array $attributes)
方法更改/设置它们.所有批量分配属性的 Eloquent 方法都使用 fill()
方法.
因此有两种方法可以在数据库中插入带有数组的基于 Eloquent 的新模型,一种使用 fill()
方法,另一种不使用.
将属性 protected $fillable = [ 'column_a', 'column_b', .. ];
添加到您的模型中.然后你可以像这样使用质量分配.
$Plan = 新计划;$Plan->fill( $array );$Plan->save();
或者你可以使用:
$plan = Plans::create( $array );
如果您没有在 creating
和 created
上注册任何 boot
方法(DB 不会触发这些),那么您也可以使用 QueryBuilder
在数据库中插入行.
//插入一个计划DB::table('plans')->insert([ $array ]);$plan = Plans::find( DB::getPdo()->lastInsertId() );//在一个查询中插入多个计划$plans = [ $plan_a_arr, $plan_b_arr, .. ];DB::table('plans')->insert($plans);
Have array which have key & value. The keys name are same database columns name.
Total of keys in an index is greater than 50.
So,not possible to save data one by one key like
$user = new User;
$user->name = 'John';
..........
.......
.......so on
$user->save();
Sample array:
Array ( [name] => 'Amit', [age] => 25, [field1] => 'val1', .... [field33] => 'how' , .... [field54] => 'sumit' )
Now, my question is that how can i save data in an model using easiest process.
$Plan=new Plans;
$Plan->fill( $array);
$Plan->save();
Note: I know that fill not working as it not defined at fillable variable of that model
The Eloquent
model has encapsulated the attributes of the object. So you can only alter/set them through the set
($model->attribute
) or the fill(array $attributes)
method. All the Eloquent methods that mass assign the attributes is using the method fill()
.
So there are 2 ways to insert new Eloquent based models with an array in the database, one that uses the fill()
method and one that doens't.
Add the attribute protected $fillable = [ 'column_a', 'column_b', .. ];
to your model. Then you can use the mass assignment like this.
$Plan = new Plans;
$Plan->fill( $array );
$Plan->save();
Or you can use:
$plan = Plans::create( $array );
If you don't have any boot
methods registered on creating
and created
(DB won't trigger these) then you also can use the QueryBuilder
to insert the rows in the database.
// insert one plan
DB::table('plans')->insert([ $array ]);
$plan = Plans::find( DB::getPdo()->lastInsertId() );
// insert multiple plans in one query
$plans = [ $plan_a_arr, $plan_b_arr, .. ];
DB::table('plans')->insert( $plans );