mercredi 14 novembre 2018

Complex relationships in Laravel (hasManyThrough through a pivot table)

So I have four tables.

  • products
  • skus
  • sku_attribute
  • attributes

Each product has many skus. Each sku has many attributes. And each attribute can have several skus associated with it. sku_attribute is a pivot table for the many to many relationship between skus and attributes.

This works fine! But now, how do I get all the attributes associated with a product?

The following code worked for me.

public function attributes()
{
    return $this->skus->flatMap(function ($sku) {
        return $sku->attributes;
    });
}

But I get an error because this doesn't return a relationship but rather a collection.

I also tried using the solution found here. But I couldn't get it to work properly because their model is slightly different than mine. (Each product has many skus, not vice versa.)

Another solution was to include a third column on sku_attributes for the product_id, but I couldn't find a way to default fill this to sku->product->id on the $sku->attach($attribute_id) method. Instead I'd have to manually call this every time, like $sku->attach($attribute_id, ['product_id' => $sku->product->id]).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire