laravel 在 Eloquent 中按关系字段执行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48321076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Perform order by relationship field in Eloquent
提问by Thelambofgoat
I want to create product filter with Eloquent.
我想用 Eloquent 创建产品过滤器。
I start like this
我是这样开始的
$query = Product::whereHas('variants')
->with('variants')
->with('reviews')
$query = $this->addOrderConstraints($request, $query);
$products = $query->paginate(20);
Where
在哪里
private function addOrderConstraints($request, $query)
{
$order = $request->input('sort');
if ($order === 'new') {
$query->orderBy('products.created_at', 'DESC');
}
if ($order === 'price') {
$query->orderBy('variants.price', 'ASC');
}
return $query;
}
However, that doesn't work, cause Eloquent is performing this query like this (information from Laravel DebugBar)
但是,这不起作用,因为 Eloquent 正在执行这样的查询(来自 Laravel DebugBar 的信息)
select count(*) as aggregate from `products` where exists
(select * from `variants` where `products`.`id` = `variants`.`product_id`)
select * from `products` where exists
(select * from `variants` where `products`.`id` = `variants`.`product_id`)
select * from `variants` where `variants`.`product_id` in ('29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48')
And so on
等等
So when I try to use sorting by price it just obvious error
所以当我尝试使用按价格排序时,它只是明显的错误
Unknown column 'variants.price' in 'order clause' (SQL: select * from
`products` where exists (select * from `variants` where `products`.`id` =
variants
.product_id
) order by variants
.price
asc limit 20 offset 0)
variants
. product_id
) 订购variants
。price
asc 限制 20 偏移 0)
So is it possible to perform relationship ordering with Eloquent or not?
那么是否可以使用 Eloquent 执行关系排序?
回答by Eduardo Stuart
This will sort the subquery. Not the "first query (the product query)".
这将对子查询进行排序。不是“第一次查询(产品查询)”。
Basically, your subquery will be:
select * from variants where product_id in (....) order by price
, and that is not what you want, right?
基本上,您的子查询将是:
select * from variants where product_id in (....) order by price
,这不是您想要的,对吗?
<?php
// ...
$order = $request->sort;
$products = Product::whereHas('variants')->with(['reviews', 'variants' => function($query) use ($order) {
if ($order == 'price') {
$query->orderBy('price');
}
}])->paginate(20);
If you want to sort product +/or variant you need to use join.
如果要对产品 +/或变体进行排序,则需要使用 join。
$query = Product::select([
'products.*',
'variants.price',
'variants.product_id'
])->join('variants', 'products.id', '=', 'variants.product_id');
if ($order === 'new') {
$query->orderBy('products.created_at', 'DESC');
}
if ($order === 'price') {
$query->orderBy('variants.price');
}
return $query->paginate(20);