按关系排序的Laravel模型

按关系排序的Laravel模型,laravel,Laravel,我的网站有评论。这些评论都有投票权 注释模型: 公共函数upvows(){ 返回$this->hasMany('App\CommentVote','comment\u id')->where('vote',1); } 公共函数子函数(){ 返回$this->hasMany('App\Comment','parent\u id'); } 注释也可以有子注释 我想知道的是,我怎样才能根据这些儿童评论的投票数对其进行排序 类似于 公共函数子函数(){ 返回$this->hasMany(

我的网站有评论。这些评论都有投票权

注释模型:

公共函数upvows(){
返回$this->hasMany('App\CommentVote','comment\u id')->where('vote',1);
}   
公共函数子函数(){
返回$this->hasMany('App\Comment','parent\u id');
}   
注释也可以有子注释

我想知道的是,我怎样才能根据这些儿童评论的投票数对其进行排序

类似于

公共函数子函数(){
返回$this->hasMany('App\Comment','parent\u id')->orderBy(upvoces);
}   

这可能吗?

使用您的孩子功能:

公共函数子函数(){
返回$this->hasMany('App\Comment','parent\u id');
}   
在控制器中,获取注释子项:

$childrens=$comment->childrens()->get();
现在,您可以使用collection方法按向上投票计数对孩子的评论进行排序:

$childrens->sortBy(函数($childrens){
$children->upvowers->count();
});
更新:附加到注释模型:

$appends
添加到注释模型中:

在您的commeht模型中:

protected$appends=['childrens'];
创建子对象的访问器(也在注释模型内):

公共函数getChildrensAttribute()
{
$childrens=$this->childrens()->get();
返回$childrens->sortBy(函数($childrens){
$children->upvowers->count();
});
}
现在,孩子们的注释将附加到家长的注释中


希望有帮助。

您可以查询按向上投票数排序的评论,包括子评论数

Comment::query()
    ->where('parent_id', $parentId) // or any way to filter by parent
    ->withCount(['upvotes' => function ($query) {$query->where('upvotes.vote', 1);}])
    ->orderBy('upvotes_count')
    ->get()

您对
->where('vote',1)
的意思是什么?投票在CommentVote表中存储为tinyint。1是向上投票,0是默认值,-1是向下投票。这使得计算评论的总分很容易。我很困惑。这正是我的children函数所要做的。很抱歉,我把你的示例函数搞混了。我已经更新了我的答案。这个解决方案将导致n+1查询,它将查询传递给sortBy的回调中每个子注释的upvotes。但是我很困惑。在我的控制器中,我将$comments数组传递给视图。这些评论可能有孩子。将排序后的子注释直接传递到视图将不起作用,因为它们是从子关系模型调用的。是否有办法将此逻辑放入注释模型中?是的,使用
appends
属性。看看我答案的更新。