Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - Laravel 5 Array with key save in model

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...