所以laravel雄辩在每个查询中使用id asc作为默认值...这对我来说是个大问题,因为在大多数情况下我需要按id desc数据进行排序
我不认为它只是我...你几乎总是希望在视图列表的顶部显示新行。
无论是新闻或用户列表还是博客帖子。
诅咒我可以使用->orderBy('id' , 'desc')但是如果我必须为每个查询写这个,我想我需要在每个项目后看到缩小!
所以我正在寻找一种干净的方式而不需要为每个模型添加东西......显然有Global Scopes但我需要为每个模型添加id,我将其视为计划B。
因此,我希望在每个查询中全局更改...有没有办法或者我应该选择B计划!?
So laravel eloquent is using id asc as default in every query ... which is a big problem for me because in most cases i need data to be sorted by id desc
And i dont think its just me ... you almost always want new rows to show in the top of the list in the view .
Whether its list of news or users or a blog posts .
Of curse i can use ->orderBy('id' , 'desc') but if i have to write this for every single query i think i would need to see a shrink after each project !
So i'm looking for a clean way and without a need to add something to each model ... apparently there is Global Scopes but i need to add id to each model which i'm ging to consider it as plan B .
So , im looking to change this globally for each and every query ... is there a way or should i go with plan B!?
最满意答案
您可以更改Laravels默认orderBy
/** * Add an "order by" clause to the query. * * @param string $column * @param string $direction * @return $this */ public function orderBy($column, $direction = 'asc') { $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [ 'column' => $column, 'direction' => strtolower($direction) == 'asc' ? 'asc' : 'desc', ]; return $this; }在/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
更改:
public function orderBy($column, $direction = 'asc')至:
public function orderBy($column, $direction = 'desc')@Grzegorz Gajda是正确的,你不应该编辑Laravel Code。 当您想要降序时,最佳解决方案是使用Laravel设计的:
->orderBy('id' , 'desc');You can change Laravels default orderBy
/** * Add an "order by" clause to the query. * * @param string $column * @param string $direction * @return $this */ public function orderBy($column, $direction = 'asc') { $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [ 'column' => $column, 'direction' => strtolower($direction) == 'asc' ? 'asc' : 'desc', ]; return $this; }In /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
Change:
public function orderBy($column, $direction = 'asc')to:
public function orderBy($column, $direction = 'desc')@Grzegorz Gajda is correct though, you shouldn't edit Laravel Code. Best solution is to use Laravel as it was designed, when you want descending:
->orderBy('id' , 'desc');更多推荐
发布评论