Sorting data with Eloquent

后端 未结 5 615
傲寒
傲寒 2021-01-11 12:49

I\'m new to laravel (switched from CI) and eloquent ORM is still a bit of a mystery at some point!

Here is my problem :

I\'d like to sort data from my db usi

5条回答
  •  天涯浪人
    2021-01-11 13:31

    I just ran into the same problem on a project I am developing. Everywhere I looked I saw the usort() or uasort() as the suggested way to solve this problem. (Collection::sort() is just a wrapper for uasort()) but that did not satisfy me because why would I use PHP to sort when SQL should do it for me with an ORDER BY clause??? I ended up implementing it this way using an getXXXAttribute() method:

    class Post extends Eloquent {
        public function comments()
        {
            return $this->hasMany('Comment');
        }
    
        public function getCommentsAttribute()
        {
            $comments = $this->comments()->getQuery()->orderBy('created_at', 'desc')->get();
            return $comments;
        }
        ...
    }
    

提交回复
热议问题