문제

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