问题描述
有包含 key & 的数组价值.键名与数据库列名相同.
索引中的键总数大于 50.
所以,不可能像
那样一键保存数据$user = 新用户;$user->name = '约翰';..................很快$user->save();
样本数组:
大批([名称] => '阿米特',[年龄] => 25,[field1] => 'val1',....[field33] => '如何' ,....[field54] => 'sumit')现在,我的问题是如何使用最简单的过程在模型中保存数据.
信息:
- 使用 Laravel 5
尝试:
$Plan=新计划;$Plan->fill($array);$Plan->save();
注意: 我知道填充不起作用,因为它没有在该模型的可填充变量中定义
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 );
方法二:QueryBuilder::insert(数组)
如果您没有在 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.
Info:
- Using laravel 5
Try:
$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.
Method 1: Mass assignment
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 );
Method 2: QueryBuilder::insert( 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 );
这篇关于Laravel 5 Array 在模型中保存密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!