Laravel 5阵列,密钥保存在模型中 [英] Laravel 5 Array with key save in model

查看:82
本文介绍了Laravel 5阵列,密钥保存在模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有具有 key&值 .键名称与数据库列名称相同.

Have array which have key & value. The keys name are same database columns name.

索引中的键总数大于50.

Total of keys in an index is greater than 50.

  • 因此,无法一键保存数据,例如

$user = new User;

$user->name = 'John';
..........
.......
.......so on

$user->save();

示例数组:


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.

  • 使用laravel 5
$Plan=new Plans;
 $Plan->fill( $array);
 $Plan->save();

注意: 我知道填充不起作用,因为它没有在该模型的可填充变量中定义

推荐答案

Eloquent模型封装了对象的属性.因此,您只能通过set($model->attribute)或fill(array $attributes)方法更改/设置它们.所有大量分配属性的雄辩方法都使用方法fill().

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().

因此,有两种方法可以在数据库中插入基于Eloquent的新模型和一个数组,一种使用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.

将属性protected $fillable = [ 'column_a', 'column_b', .. ];添加到模型中.然后,您可以使用这样的质量分配.

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();

或者您可以使用:

$plan = Plans::create( $array );

方法2:QueryBuilder :: insert(array)

如果您没有在creatingcreated上注册任何boot方法(DB不会触发这些方法),那么您也可以使用QueryBuilder在数据库中插入行.

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阵列,密钥保存在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆