I'm making a site with Laravel 5.2
I would like to do is
INSERT
3 rows at the same time- The new 3 rows have to contain timestamp
created_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?- By
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. - How can I pass an array of 3 items to
create
method in order to fire timestamps? - Is it a good idea to call
create
inside the loops?
PS. protected $guarded = []
was assigned to empty array so would not receive Mass Assignment Exception.
Thank you so much.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire