php - laravel 5中的三级雄辩关系orderBy
问题描述
在我的数据库中,我有以下表格:
quotes
-id
-quote_title
...
quote_items
-id
-quote_id
-product_id
products
-id
-product_name
-product_category_d
我想要实现的是使用product_category_id 对我的查询结果进行排序。
下面是查询。
$query = Quote::query();
$query->whereHas('quote_item' , function ($query) {
$query->whereHas('product' , function ($query) {
$query->orderBy('product_category_id');
});
});
$temp= $query->find($id);
结果没有显示任何错误,但不是按顺序排列的。
报价型号:
class Quote extends Model
{
public function QuoteItem()
{
return $this->hasMany('app\QuoteItem');
}
}
报价单型号:
class QuoteItem extends Model
{
public function Quote()
{
return $this->belongsTo('app\Quote');
}
public function Product()
{
return $this->belongsTo('app\Product');
}
}
产品型号:
class Product extends Model
{
public function QuoteItem()
{
return $this->hasMany('app\QuoteItem');
}
}
解决方案
我建议为Quote
模型创建专用范围:
public function scopeOrderByCategory($query)
{
return $query
->join('quote_items', 'quote_items.quote_id', '=', 'quotes.id')
->join('products', 'products.id', '=', 'quote_items.product_id')
->orderBy('products.product_category_id');
}
然后,您可以在选择报价并需要按产品类别对其进行排序时使用它:
$quotes = Quote::orderByCategory()->get();
quote_items
但是您必须对这个范围内连接和products
表的事实保持谨慎。
您可以在此处阅读有关本地 Eloquent 作用域的更多信息。
推荐阅读
- javascript - 使用 AJAX 渲染 ASP.NET PartialView 不起作用
- arrays - 如何输出一系列分割线 Power Automate
- javascript - 正则表达式使每个单词的首字母大写,包括特殊字符
- python - Python 文件缓冲区存储在哪里?
- java - SMS Retriever API 中已发布 APK 上的 HASH 字符串键
- laravel - 从 VueRouter 访问 Vuex 状态
- r - 如何按年和月绘制平均密度
- sql - 计算每列中字符串的出现次数(Postgres)
- r - 如何使 selectInput 选择覆盖 dq_accordion?
- c# - 随机分配不同价值的钞票以适合总价值