php - 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!
解决方案
为 和Product
创建模型。PriceList
User
在您的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);
推荐阅读
- php - Laravel 5.6 中的验证
- python - Django AttributeError:“光标”对象没有属性“_last_executed”
- hibernate-search - 休眠搜索单向关联
- ios - 访问 NSDictionary 中的信息
- filter - 为什么power bi图中不同的轴会影响计算
- java - @JsonFormat 使用不正确的时区转换日期
- c# - 如何执行实体框架跟踪sql
- c++ - 对 2D int 数组的特定列进行排序 (C++)
- javascript - 角度检查数组是否包含具有特定变量值的对象
- android - 活动退出时的 RecyclerView 动画