Laravel模型订单按关系

时间:2019-07-17 18:15:26

标签: laravel

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

评论模型:

public function upvotes() {
    return $this->hasMany('App\CommentVote', 'comment_id')->where('vote', 1);
}   
public function children() {
    return $this->hasMany('App\Comment','parent_id');
}   

评论也可以有子评论。

我想知道的是如何将这些子注释按投票数排序?

类似...

public function children() {
    return $this->hasMany('App\Comment','parent_id')->orderBy(upvotes);
}   

这可能吗?

2 个答案:

答案 0 :(得分:1)

具有孩子功能:

public function children() {
    return $this->hasMany('App\Comment','parent_id');
}   

在您的控制器中,获取注释子项:

$childrens = $comment->children()->get();

现在,您可以使用sortBy收集方法按照投票数对孩子的评论进行排序:

$childrens->sortBy(function($children){
    $children->upvotes->count();
});

更新:附加到评论模型:

$appends添加到评论模型:

在您的商业模式内:

protected $appends = ['childrens'];

创建子项的访问器(也在评论模型中):

public function getChildrensAttribute()
{
    $childrens = $this->childrens()->get();
    return $childrens->sortBy(function($children){
        $children->upvotes->count();
    });
}

现在,孩子的评论将被添加到父评论中。

希望有帮助。

答案 1 :(得分:0)

您可以查询按投票次数排序的评论,包括子评论的数量。

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()
相关问题