Home > Enterprise >  Laravel get collection of created/updated rows
Laravel get collection of created/updated rows

Time:02-22

new to laravel.

My use case:

  • Update multiple rows (say: resources table).
  • Create multiple users (users table).
  • Retrieve ids of created users

What I currently did:

  • First, Update the resources table whereIn('id', [1,2,3,4]). (Update eloquent)
  • Second, Get array of the updated resources (Another eloquent: Resource::whereIn('id', [1,2,3,4])->get()->toArray())
  • Bulk create a users. Refers to the resources collection above. (Another eloquent: User::create($resources))
  • Lastly, get the ids of the created users (Not resolved yet. But I might have to use another eloquent query)

All in all, there are 4 Eloquent queries, which I want to avoid, because this might have performance issue.

What I wanted to do is that, On first step(Update), I should be able to get a collection of models of the affected rows (But I can't find any reference on how to achieve this). And then use this collection to create the users, and get the users ids in one query with User::create() so that I will have 2 queries in total.

CodePudding user response:

To save multiple records with one querry you can use

DB::table('table_name')->insert($data);

Since this won't be an eloquent method, you should pass all the fields including created_at and updated_add.

I don't know what is the method name for update.

CodePudding user response:

There is no need to invent performance problems that do not exist.

Update or Insert return only count of affected rows. Commands Select, Insert, Update performed separately. This is a SQL issue, not Laravel.

For single inserts (if you want add one row) you can use insertGetId method of a model.

For example,

$id = User::insertGetId([
    'email' => '[email protected]',
    'name' => 'john'
]);

But you get only ID of record. You need to run select to get full data of the row.

  • Related