質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top