Laravel:orderBy 带有集合的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42854788/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:35:29  来源:igfitidea点击:

Laravel: orderBy a column with collections

phplaraveleloquentlaravel-5.4

提问by Hamed Kamrava

I need to OrderBy a column with collection.

我需要按一个带有集合的列排序。

I need to orderBy(updated_at, 'desc')all posts which owned by current logged user.

我需要orderBy(updated_at, 'desc')当前登录用户拥有的所有帖子。

Here is my code :

这是我的代码:

$posts = auth()->user()->posts->sortByDesc('updated_at');

Here is User model :

这是用户模型:

class User extends Authenticatable
{
    public function posts()
    {
      return $this->hasMany(Post::class);
    }
}

It doesn't return any errors also doesn't sort !

它不会返回任何错误也不会排序!

Any helps would be great appreciated.

任何帮助将不胜感激。

P.S:

PS:

I know I can achieve this with :

我知道我可以通过以下方式实现这一目标:

$posts = Post::where('user_id', auth()->user()->id)->orderBy('updated_at', 'desc')->get();

But I would like to do the same thing with collections.

但我想对集合做同样的事情。

回答by DevK

So this is how you sort with SQL:

这就是您使用 SQL 进行排序的方式:

$posts = auth()->user()->posts()->orderBy('updated_at', 'DESC');

And with collections:

并带有集合:

$posts = auth()->user()->posts->sortByDesc('updated_at');

I've tested the 2nd one and it works as intended for me.

我已经测试了第二个,它按我的预期工作。

Documentation:https://laravel.com/docs/6.x/collections#method-sortbydesc
*Its available since Laravel 5.1

文档:https :
//laravel.com/docs/6.x/collections#method-sortbydesc *从 Laravel 5.1 开始可用

回答by Jesse de gans

Try adding the following to your User model

尝试将以下内容添加到您的 User 模型中

public function posts_sortedByDesc(){
      return $this->hasMany(Post::class)->sortByDesc('updated_at');
   }

Then get the posts by calling posts_sortedByDescinstead of posts

然后通过调用posts_sortedByDesc而不是 获取帖子posts

回答by Hamed Kamrava

@devk is right. What I wrote in the first post is correct.

@devk 是对的。我在第一篇文章中写的是正确的。

The problem was in DataTablesin the the view.

问题出在视图中的数据表中。

It needed to add this line to the Datatables options:

它需要将此行添加到 Datatables 选项中:

"order": [[ 5, 'desc' ]], // 5 is the `updated_at` column (the sixth column in my case)

So this is working fine :

所以这工作正常:

$posts = auth()->user()->posts->sortByDesc('updated_at');