Update relationship inside relationship hasMany values

Viewed 38

So I was wondering how do I need to update relationship inside relationship values. For example I have first relationship:

class Code {
  public function item()
  {
     return $this->hasOne(UserItem::class, 'code_id')
  }
}

And then there is other nested relationship inside UserItem::class:

class UserItem {
  public function serials()
  {
     return $this->hasMany(ItemSerial::class, 'user_item_id', 'id');
  }
}

And then I recieve request values:

'item_serials' =>
  array (
    0 => 'test1',
    1 => 'test2'
  ),

And I need to updateOrCreate values of serials relationship. Something like this:

   foreach ($data['item_serials'] as $serial) {
                $code->item->serials->updateOrCreate([
                    'serial' => $serial
                ]);
    }

But this obviously doesn't work.

1 Answers

update or create method are static eloquent methods and for useing static methods from relationship you most use the relation method not property,so change your code to:

foreach ($data['item_serials'] as $serial) {
                $code->item->serials()->updateOrCreate([
                    'serial' => $serial
                ]);
    }
Related