Laravel: Insert multiple records with auto fill created_at & updated_at
·
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:-
Model::create($insert_data)But it doesn't create any entry in DB.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);
更多推荐
所有评论(0)