I'm making a site with Laravel 5.2
I would like to do is
INSERT
3 rows at the same timecreated_at
updated_at
.With the Query Builder
method insert
, Yes, it does insert 3 rows at once by passing an array like:
GroupRelation::insert([
[
'application_id' => $applications[0]->a_id,
'group_id' => $group->id,
],
[
'application_id' => $applications[1]->a_id,
'group_id' => $group->id,
],
[
'application_id' => $applications[2]->a_id,
'group_id' => $group->id,
],
]);
The code above works fine. But this cannot touch the timestamp. Which means the created_at
updated_at
will be null.
However, if I changed the method insert
to create
:
GroupRelation::create([
...
]);
It received the error:
ErrorException in Model.php line 2983:
preg_match() expects parameter 2 to be string, array given
If I'm not wrong, it seems like create
can just accept 1 row at the same time, right?
I know insert
is not a part of Eloquent
. Eloquent
fires timestamps but Query Builder
does not.
So my questions are:
insert
method can accept 3 rows at one time, but how can I fire the timestamp manually? 1.
I've tried to add 'created_at' => date('Y-m-d H:i:s'),
at each items of the array. But the controller is unclear and horrible. create
method in order to fire timestamps? create
inside the loops? PS. protected $guarded = []
was assigned to empty array so would not receive Mass Assignment Exception.
Thank you so much.
insert()
is a part of Query Builder, so it doesn't use Eloquent features.
You can't pass 3 items to create()
method, only one. And using create()
inside loops is terrible idea.
You should add these fields manually when doing bulk insertion:
[
'application_id' => $applications[0]->a_id,
'group_id' => $group->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
],
You may use dateTime
class :
[
'application_id' => $applications[0]->a_id,
'group_id' => $group->id,
'created_at' => new \dateTime,
'updated_at' => new \dateTime,
],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With