通过使用与 laravel 的关系,在其他 table 的帮助下从 table 订购数据?

Ordering data from a table with the help of other table by using relationships with laravel?

我有带有查询的控制器:

$Comments = Comment::orderBy('id_parent', 'asc')->get();

我有评论模型:

class comment extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function votes()
    {
        return $this->hasMany('App\Vote', 'comment_id', 'id_comment');
    }
}

我想检索以特定方式排序的评论数据,每条评论都有不同用户投票的多票,因此计数('vote')是每条评论的投票数。问题是我对如何调用模型中的特定投票函数感到困惑,以便它可以计算列投票并将其排序为 asc 或 desc。

最后我可以让 $Comments 也按总票数排序。

您可以试试:

$Comments = Comment::withCount('votes')->orderBy('votes_count', 'asc')->get();

withCount() 方法用于计算关系中结果的数量而不实际加载它们,这将在结果模型上放置一个 {relation}_count 列。

使用排序方式:

$comments=Comment::with('votes')->get()->sortBydesc('votes');
foreach($comments as $comment)
{
   echo $comment->votes->count('vote');
}