我需要一种按两列对模型进行排序的方法(但不是按x,y排序)。我有一个可以在结果中‘提升’模型的priority列,还有一个标准的created_at,当没有设置priority时,它应该是排序键。我找到的唯一方法就是与工会合作。
使用类似如下的查询:
(SELECT * FROM `charts` WHERE priority IS NOT NULL ORDER BY priority ASC)
UNION (SELECT * FROM `charts` WHERE priority IS NULL AND created_at IS NOT NULL ORDER BY CREATED_AT ASC)
UNION (SELECT * FROM `charts` WHERE created_at IS NULL)所以我试着这样做:
public function scopeSortPriority($query)
{
return $query->whereNotNull('priority')
->orderBy('priority')
->union($query->whereNull('priority')
->whereNotNull('created_at')
->orderBy('created_at'))
->union($query->whereNull('priority')
->whereNull('created_at'));
}但令人遗憾的是,它并不起作用。
有没有其他方法可以在SQL中实现我想要的功能?否则-我应该如何重新构建这个作用域以使其工作?
发布于 2017-06-27 22:11:06
问题是您在联盟中使用了$query。
如果您知道查询和联合的公共部分总是\DB::table('charts'),那么您可以这样做:
$query->whereNotNull('priority')
->orderBy('priority')
->union(\DB::table('charts')->whereNull('priority')
->whereNotNull('created_at')
->orderBy('created_at'))
->union(\DB::table('charts')->whereNull('priority')
->whereNull('created_at'));如果$query是相同的,但可以更改,您可以这样做:
$query2 = clone $query;
$query3 = clone $query;
$query->whereNotNull('priority')
->orderBy('priority')
->union($query2->whereNull('priority')
->whereNotNull('created_at')
->orderBy('created_at'))
->union($query3->whereNull('priority')
->whereNull('created_at'));在这两种情况下,sql的输出都是:
(select * from `charts` where `priority` is not null order by `priority` asc) union (select * from `charts` where `priority` is null and `created_at` is not null order by `created_at` asc) union (select * from `charts` where `priority` is null and `created_at` is null) https://stackoverflow.com/questions/44776744
复制相似问题