Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data with Eloquent

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 using Eloquent.

I have a table posts and a table comments (post has many comments and comment belongs to posts)

Every comment has a timestamp (=> created_at field) and I'd like to order things as follow :

(we're on profil page so $user->id is the id of the user (obviously))

I want every post from posts where this user made a comment and order all those post by the created_at field of the comment

I really want to use Eloquent fully, or at least Fluent, and I don't know the right way to do so.

I hope I'm being clear, and thank you for your time!

like image 722
Pretty Good Pancake Avatar asked Mar 20 '13 20:03

Pretty Good Pancake


2 Answers

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;
    }
    ...
}
like image 92
normany Avatar answered Oct 20 '22 09:10

normany


I had the same problem before but it was a one-to-one relationship. This post helped me. I ended up using a join. My code was like this:

$data = Posts::join('comments', 'comments.post_id', '=', 'posts.id')
        ->order_by('comments.created_at')
        ->get(array('comments.field1 as field1', 'posts.field2 as field2'));
like image 25
dakine Avatar answered Oct 20 '22 11:10

dakine