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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?