将所有查询的默认ORDER BY从ASC更改为DESC(Changing default ORDER BY from ASC to DESC globally for all queries)

编程入门 行业动态 更新时间:2024-10-26 02:36:27
将所有查询的默认ORDER BY从ASC更改为DESC(Changing default ORDER BY from ASC to DESC globally for all queries)

所以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');

更多推荐

本文发布于:2023-08-07 04:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DESC   ASC   ORDER   Changing   queries

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!