Home > Back-end >  Bulk updates of related models
Bulk updates of related models

Time:03-22

Update single...

$modelA->update(['status_id' => 1])

Update multiple...

ModelA::whereIn('id', $data['ids'])->update(['status_id' => 1])

SO

Updating a model related to a single row can work as follows...

$modelA->relatedModel()->update(['status_id' => 1])

($modelA instance is supplied via route model binding, and the relatedModel() method/relationship is defined in the "ModelA" model)

BUT

When attempting the following,

ModelA::whereIn('id', $data['ids'])->relatedModel()->update(['status_id' => 1])

I get an error

Call to undefined method Illuminate\Database\Eloquent\Builder::relatedModel()

It seems that I am not really understanding what is being returned by

ModelA::whereIn('id', $data['ids'])

So what I'm looking for is a method of updating the related models of multiple rows (obviously without a loop of any kind).

CodePudding user response:

whereIn() and many other methods, like where(), has(), with(), etc. returns a Builder instance, which lets you chain additional queries. You cannot access ModelA instance methods, like relatedModel() on a Builder instance.

You will need to call ->get(), and iterate the results calling relatedModel()->update():

foreach(ModelA::whereIn('id', $data['ids'])->get() as $modelA) {
  $modelA->relatedModel()->update(['status_id' => 1]);
}

Alternatively, if you'd like a single-liner without a loop, you will need to query the ModelB model (or whatever relatedModel() is) directly:

ModelB::whereIn('model_a_id', $data['ids'])->update(['status_id' => 1]);

Note: Assumed that ModelB has a model_a_id. If it doesn't, you can use the whereHas() method instead:

ModelB::whereHas('modelA', function ($query) use ($data) {
  return $query->whereIn('model_a.id', $data['ids'];
})->update(['status_id' => 1]);

Note: Again, made some assumptions on your table/column names; adjust as required.

  • Related