以多态关系排序


Order by and Paginate in polymorphic relation

我有三个表:postscommentsscores

comments表:

 id | body | user_id | commentable_type | commentable_id | created_at

scores表格:

 id | score | user_id | scoreable_type | scoreable_id | created_at

我想获得一个特定帖子的评论,但这些评论应该根据他们的分数(投票)排序!

到目前为止,我已经有了这个代码,但评论并没有按分数排序!

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

编辑:在我的Comment模型类中,我有:

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

我可以得到所有的评论,然后把它们分类收集起来,但这是浪费资源。。。

谢谢!

尝试在回调中添加orderBy进行查询,方法如下:

$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;