I
I
IceJOKER2014-11-09 17:13:58
Laravel
IceJOKER, 2014-11-09 17:13:58

How to sort by related table field in laravel?

There are models - Post | Comment
Related respectively as Post.hasMany and Comment.belongsTo, how can I display all Post sorted by number of comments ?
+ pagination required

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
cha-cha, 2014-11-09
@cha-cha

stackoverflow.com/questions/24208502/laravel-order...

R
Roman Sokharev, 2014-11-09
@greabock

You are trying to select a post with comments.
Do you need comments? So choose comments.

Comment::whereHas('post', function( $query ) use ($id) {
        $query->whereId($id);
})->orderBy('created_at')->paginate(0, 15);

Otherwise, output order can and can be handled, but not pagination.

S
Sergey Gladkovskiy, 2014-11-10
@SMGladkovskiy

Try like this:

$posts = Post::with('comments')
            ->join('comments', 'comments.post_id', '=', 'posts.id')
            ->select('posts.*', 'comments.*')
            ->groupBy('posts.id')
            ->orderBy(DB::raw('COUNT(`posts`.`id`)'), 'asc')
            ->paginate(10);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question