Answer a question

I am trying to save multiple records in DB and have an array which looks like:-

$insert_data = array(
array(record 1),
array(record 2),
array(record 3)
)

Now, I tried two options:-

  1. Model::create($insert_data) But it doesn't create any entry in DB.
  2. Model::insert($insert_data) It's creating entry in DB with null datestamps.

I wanna insert multiple records with valid timestamps.

TIA

Answers

create() is a function from Eloquent, insert() - Query Builder.

You probably do not use Eloquent when inserting data, in this case you should add timestamps manually.

If you do not want to do this, but you still need filled timestamps, use this trick:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

Or, you can add timestamp like this :

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 
         'rep'=>'4096',
        'created_at'=> $now,
        'updated_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 
         'rep'=>'2048',
         'created_at'=> $now,
         'updated_at'=> $now
       ),
    //...
);

Coder::insert($data);
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐