简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM