清除Laravel的订单 [英] Clear Laravel's orderBy
问题描述
我有一个通用函数,可以为我提供通用查询集,例如:
I have a generic function which gives me generic querysets, something like:
class Model extends Eloquent {
public static function get_queryset(){
$queryset = self::where('foo','=','bar');
// Do tons of stuff with the query and then...
return $queryset->orderBy('somefield');
}
}
此函数在我的项目中随处使用,但是在特定的地方,我需要使用此查询集,但要更改 ORDER BY,就像这样:
This function is used everywhere my project, but in a specific point I need to use this queryset but changing the ORDER BY, much like this:
public static function get_specific_field(){
return self::get_queryset()->select('singlefield')->orderBy('singlefield');
}
如果我运行此代码,则由于"somefield"不在SELECTed字段上,因此ORDER BY只会追加到前一个代码上并生成无效的查询.即:
If I run this code, the ORDER BY will just append onto the previous and generate an invalid query, since the "somefield" is not on the SELECTed fields. i.e.:
SELECT singlefield FROM table ORDER BY somefield ASC, singlefield ASC
如何清除订单,以便重新使用查询集?
How do I clear the orderBy so I can just reuse querysets?
推荐答案
我同意应该在查询构建器中添加clearOrderBy()
方法.但是,由于orderbys的注册表是Illuminate\Database\Query\Builder
上的公共财产,因此您实际上可以今天自己将其清除.技巧是访问基本查询对象:
I agree there should be a clearOrderBy()
method added to the query builder. However because the registry of orderbys is a public property on Illuminate\Database\Query\Builder
you actually can clear it yourself today. The trick is getting access to the base query object:
$query = YourModel::where('status', 1)->orderBy('created_at','desc');
// ... lots of other code, something needs to reset the order by ...
$query->getQuery()->orders = null;
$query->orderBy('other_column', 'desc');
在其他时间,例如,在处理关系查询时,您需要访问基本查询(Illuminate\Database\Query\Query
).例如:
At other times, for example when manipulating a relation query, you need to get to access the base query (Illuminate\Database\Query\Query
). So for example:
$query = YourModel::find(1)->load('children', function ($query) {
$query->getBaseQuery()->orders = null;
});
就这样.我也打算为clearOrderBy()
提交PR.
Thats it. I plan to submit a PR for a clearOrderBy()
as well.
这篇关于清除Laravel的订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!