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

Viewed 28

i'm trying to create a simple relationship between tables :

- attribute_products -
    id
    name

- products -
    id
    name
    price

pivot table to link them :

- attribute_product_value -
    attribute_type_id
    value
    product_id 

Products Model

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

attribute_products model

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

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

1 Answers

As per Laravel documentation if the intermediate table has extra columns it needs to be specified while defining relationship

//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();
}

To access the column in the intermediate table


$attributeProduct = AttributesProduct::find(1);

foreach($arrtibutesProduct->products as $prouct)
{
    $product->pivot->value;
}

You can customise pivot attribute name

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

Related