我有一个答案模型

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


我也有一个UpvoteAnswer模型

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


我有一个名为upvote_answers的表,该表具有诸如id,user_id,answer_id(其他答案表,此ID指向该表)的列,以及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();

09-25 18:17