首页 > 解决方案 > 如何从数据透视表中获取“价值”字段(产品到“价值”)?-Laravel

问题描述

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

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

属性产品模型

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

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

标签: laravel

解决方案


根据 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


推荐阅读