Warm tip: This article is reproduced from serverfault.com, please click

其他-我如何从数据透视表中获取“值”字段(产品为“值”)?

(其他 - how can I get the "value" field from the pivot table (product to "value")? -Laravel)

发布于 2020-11-28 03:14:24

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

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

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

Questioner
Phú
Viewed
11
Donkarnash 2020-11-28 11:28:56

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