douniao8687 2015-01-20 20:13
浏览 58
已采纳

关系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 ?

  • 写回答

1条回答 默认 最新

  • dslf46995 2015-01-20 20:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable