Laravel 在两个表之间使用 eloquent 计数

Laravel count using eloquent between two tables

我有一个答案模型

 public function upvote_answers()
    {
        return $this->hasMany('App\UpvoteAnswer');
    }

我也有一个 UpvoteAnswer 模型

public function answer()
    {
        return $this->belongsTo('App\Answer');
    }

我有一个名为 upvote_answers 的 table,其中包含 iduser_id[= 等列29=]、answer_id(不同的答案 table,这个 id 引用那个 table),以及 upvote(布尔值 1 或 0)

我想要统计个人答案的赞成票和反对票,所以我这样做了

$answer = UpvoteAnswer::find($answerid) ;
$counting = $answer->upvote_answers->count();
echo $counting;

我试图回应一个答案的总计数,但这似乎不起作用,我正在尝试进行预加载,我该如何构建它?

答案模型:

public function upvote_answers()
{
    return $this->hasMany('App\UpvoteAnswer', 'answer_id', 'id')->where('upvote', 1);
}

public function downvote_answers()
{
    return $this->hasMany('App\UpvoteAnswer', 'answer_id', 'id')->where('upvote', 0);
}

那你可以这样算:

$upvote = $answer->upvote_answers->count();
$downvote = $answer->downvote_answers->count();