Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent insert 3 rows at once with timestamp

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:

  1. insert method can accept 3 rows at one time, but how can I fire the timestamp manually?
  2. 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.
  3. How can I pass an array of 3 items to create method in order to fire timestamps?
  4. 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.

like image 201
Benyi Avatar asked Dec 28 '16 16:12

Benyi


Video Answer


2 Answers

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(),
],
like image 92
Alexey Mezenin Avatar answered Sep 29 '22 08:09

Alexey Mezenin


You may use dateTime class :

[
    'application_id'    => $applications[0]->a_id,
    'group_id'          => $group->id,
    'created_at'        => new \dateTime,
    'updated_at'        => new \dateTime,
],
like image 31
Rashedul Islam Sagor Avatar answered Sep 29 '22 07:09

Rashedul Islam Sagor