【问题标题】:how can I get the "value" field from the pivot table (product to "value")? -Laravel如何从数据透视表中获取“价值”字段(产品到“价值”)? -Laravel
【发布时间】:2021-03-10 18:01:18
【问题描述】:

我正在尝试在表之间创建一个简单的关系:

- attribute_products -
    id
    name

- products -
    id
    name
    price

数据透视表链接它们:

- attribute_product_value -
    attribute_type_id
    value
    product_id 

产品型号

 public function attributeProduct(){
        return $this->belongsToMany(AttributeProduct::class,'attribute_product_values','product_id','attribute_id');
    }

attribute_products 模型

public function product()
    {
        return $this->belongsToMany(Product::Class,'attribute_product_values','attribute_id','product_id');
    }

如何从数据透视表中获取“价值”字段(产品到“价值”)?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    根据 Laravel 文档,如果中间表有额外的列,则需要在定义关系时指定它

    //Product
    public function attributeProduct(){
        return $this->belongsToMany(
            AttributeProduct::class,
            'attribute_product_values',
            'product_id',
            'attribute_id'
        )
        ->withPivot('value');
        //If you want created_at and updated_at on pivot table
        ///withTimestamps();
    }
    
    
    //AttributesProduct
    
    public function product()
    {
        return $this->belongsToMany(
            Product::Class,
            'attribute_product_values',
            'attribute_id',
            'product_id'
        )
        ->withPivot('value');
        //If you want created_at and updated_at on pivot table
        ///withTimestamps();
    }
    

    访问中间表中的列

    
    $attributeProduct = AttributesProduct::find(1);
    
    foreach($arrtibutesProduct->products as $prouct)
    {
        $product->pivot->value;
    }
    

    可以自定义pivot属性名

    https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      相关资源
      最近更新 更多