Search code examples
laraveleloquentlumenlaravel-collection

Update model which having multiple rows


I have an object model which have multiple rows like result getting with this query:

$cities = City::whereIn('id' , [1,2,3])->get();

What I want to do is update each row with the same value without using each because each is making a query on each row, so in above query I will have 3 queries.

Instead of doing this:

$cities->each->update(['name' => 'test']);

I want to do something like this as I already have the model object, but it doesn't work:

$cities->update(['name' => 'test']);

Instead I must do something like this to make it work:

City::whereIn('id' , $cities->pluck('id'))->update(['Avatar' => 'test']);

My question is; Why can't I use this:

$cities->update(['name' => 'test']);

Solution

  • When you use ->get() method you are getting not a model, but an collection of models.

    There is no such thing as multiple row models. Models has only one "row".