Abdul Basit
Abdul Basit

Reputation: 374

Link table in relationship laravel

I am making an accounting system in Laravel in which I have products, and clients. I want to set separate price of each product for each client i.e without setting percentage for each discount. For this I have made a separate table for prices.

My table schema is

Products(id,name,category,stock)
Clients(id,name,email,city)
Prices(product_id,price_id,price(String))

But I am unable to set Laravel relationship . I am making a prices function in product table as

public function prices()
{
    return $this->belongsToMany('Client','prices','product_id','client_id');
}

and in client table as

public function prices()
{
    return $this->belongsToMany('Product','prices','client_id','product_id');
}

but I am unable to use $product->prices to get prices etc. How can I use this kind of relationship in Laravel ?

Upvotes: 1

Views: 915

Answers (1)

Bogdan
Bogdan

Reputation: 44536

If you have many-to-many relationship between your products and your clients, and you need to work with any additional columns on your pivot table, you need to specify that with the relation definition. So for example in your Product model you might have this:

public function prices()
{
    return $this->belongsToMany('Client', 'Prices', 'product_id', 'client_id')->withPivot('price');
}

The withPivot method tells Laravel you need the price column to be fetched, in addition to the relation ID columns. To get the prices for a product you can then do the following:

foreach($product->prices as $price)
{
   $price->pivot->price; // to get the price for each individual client
}

To do this for the Client model, you would need the following (specifing again the price column as part of the relation):

public function prices()
{
    return $this->belongsToMany('Product', 'Prices','client_id','product_id')->withPivot('price');
}

And to get the prices for a client:

foreach($client->prices as $price)
{
   $price->pivot->price; // to get the price for each individual product
}

You can read more about this in the Laravel Docs.

Upvotes: 0

Related Questions