首页 > 解决方案 > Laravel 5.6 Create multiple relationships

问题描述

Hi I have a complex question. I have been working with Laravel for only a week. And I try to build price lists for customers.

I have 5 tables:

price_lists:
  id
  title

---------------------------
price_lists_products:
  id
  product_id
  price_lists_id
  price
  percent

---------------------------
price_lists_users:
  id
  user_id
  price_lists_id

---------------------------
products:
  id
  title
  price
---------------------------
users:
  id
  name

And I have to put them together like this:

There are a few price lists

Each price list is associated with products + price

Each user can associate up to 5 price lists

In product view and in the list, I need to show the user the product with the cheapest price that is set for him in the price lists

For example:

I have a book that belongs to 5 different price lists and each price list, a different price.

And there is a user associated with 3 price lists.

I want the user to get the cheapest price in the price lists to which he belongs

I hope this is understandable, I have no idea how to approach it, I would be happy if you can help me with it, thanks!

标签: phpmysqllaravellaravel-5

解决方案


为 和Product创建模型。PriceListUser

在您的Product模型中,创建多对多关系以获取相关PriceList集合:

public function pricelists()
    {
        return $this->belongsToMany('App\PriceList')->withPivot('price', 'percent');
    }

在您的PriceList模型中,创建多对多关系以获取相关User集合:

public function users()
    {
        return $this->belongsToMany('App\User');
    }

再次在Product模型中,您可以获得最便宜的价格,如下所示:

// get the cheapest listing by user_id, you can set default to logged in user
public function cheapestprice($user_id){
    $this->pricelists->whereHas('users', function ($query) {
        $query->where('user_id', $user_id);
    })->orderBy('price_lists_products.price','ASC')->first()->price;
}

最后,使用 Product 对象,您可以获得最便宜的价格:

Product::first()->cheapestprice(Auth::user()->id);

推荐阅读