【问题标题】:Laravel 4: Get all product attributes with relationship tableLaravel 4:使用关系表获取所有产品属性
【发布时间】:2013-05-22 19:18:23
【问题描述】:

我有以下表格:

products (
    id
)

attributes (
    id
    name
    value
)

products_attributes (
    product_id,
    attribute_id
)

而且我需要能够查询特定产品的所有属性。我尝试使用 FLUENT QUERY BUILDER 执行此操作,但我迷失在自己的代码中。

有人可以帮我举个例子吗?

【问题讨论】:

    标签: php mysql laravel entity-attribute-value


    【解决方案1】:

    通常您会为两个实体创建模型,您可以在其中指定关系:

    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');
        }
    }
    

    belongsToMany() 方法建立了多对多关系。第一个参数指定相关模型类名称,第二个参数指定保存两个实体之间连接的数据库表的名称。

    要查找 ID 为 1234 的产品,您可以这样获取它:

    $product = Product::find(1234);
    

    然后您可以像这样神奇地访问它的所有属性:

    $attributes = $product->attributes;
    

    更多信息可以参考the documentation

    【讨论】:

    • 我会小心的,因为 Eloquent 使用内部的protected $attributes = array();,这很可能会破坏这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2018-10-11
    相关资源
    最近更新 更多