Ali Sherafat
Ali Sherafat

Reputation: 3855

Order by and Paginate in polymorphic relation

I have three tables: posts, comments and scores

comments table:

 id | body | user_id | commentable_type | commentable_id | created_at

scores table:

 id | score | user_id | scoreable_type | scoreable_id | created_at

i want to get comments for a specific post but these comments should be ordered by their score(vote)!

By now i have this code but comments are not sorted by their score!

$limit = 2;
$post = Post::with(['comments' => function ($query) use ($limit) {
    $query->paginate($limit);
}])->find(3);
return $post;

EDIT: and in my Comment model class i have:

public function scores() {
    return $this->morphMany(Score::class, 'scoreable');
  }

I can get all comments and then sort them in collection but it's waste of resources...

Thanks!

Upvotes: 0

Views: 1615

Answers (2)

Jose Rojas
Jose Rojas

Reputation: 3520

Try adding orderBy to query inside the callback, this way:

$limit = 2;

$post = Post::with([
    'comments.score' => function ($query){
        $query->orderBy('score', 'DESC');
    }, 
    'comments' => function ($query) use ($limit) {
        $query->take($limit);
    }
])->find(3);

return $post;

Upvotes: 1

Alex Harris
Alex Harris

Reputation: 6392

$limit = 2;
$post = Post::with(['comments.scores' => function ($query) use ($limit) {
    $query->orderBy('score', 'DESC');->paginate($limit);
}])->find(3);
return $post;

Upvotes: 0

Related Questions