Home > Back-end >  hasMany relationship with multiple models?
hasMany relationship with multiple models?

Time:01-21

Here's the problem:

/**
 * Get all of the clothes for the Selling
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function clothes(): HasMany
{
    return $this->hasMany(Cloth::class);
}

I need to make this relationship accept more than one type of model, something like this:

/**
 * Get all of the products for the Selling
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function products(): HasMany
{
    return $this->hasMany([Cloth::class, Accessory::class]);
}

At first i thought a polymorphic relation would do the trick but i don't think it will. Should i make a pivot table?

CodePudding user response:

That's de good example to polymorphic relations, because you need to specify the model and the id of that model.

Documentation Laravel

CodePudding user response:

I solved it just by defining another relationship in the model:

 /**
 * Get all of the accessories for the Selling
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function accessories(): HasMany
{
    return $this->hasMany(Accessory::class);
}

And then merge them with a function:

/**
 * Get all of the products for the Selling
 *
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function products(): Collection
{
    return $this->clothes->merge($this->accessories);
}
  •  Tags:  
  • Related