Search code examples
phpmysqllaravelentity-attribute-value

Laravel 4: Get all product attributes with relationship table


I've got the following tables:

products (
    id
)

attributes (
    id
    name
    value
)

products_attributes (
    product_id,
    attribute_id
)

And I need to be able to query for all of the attributes of a specific product. I tried doing this with the FLUENT QUERY BUILDER but I'm getting lost in my own code.

Can someone help me out with an example?


Solution

  • Usually you would create models for both of your entities, in which you can specify the relationships:

    class Product extends Eloquent
    {
        protected $table = 'products';
    
        public function attributes()
        {
            return $this->belongsToMany('Attribute', 'products_attributes');
        }
    }
    
    class Attribute extends Eloquent
    {
        protected $table = 'attributes';
    
        public function products()
        {
            return $this->belongsToMany('Product', 'products_attributes');
        }
    }
    

    The belongsToMany() method sets up a many-to-many relationship. The first parameter specifies the related model class name, the second one the name of the database table that holds the connections between the two entities.

    To find a product with ID 1234, you would fetch it like this:

    $product = Product::find(1234);
    

    You can then magically access all of its attributes like this:

    $attributes = $product->attributes;
    

    For more information, you can refer to the documentation.