我有一个答案模型
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)
我想要个人答案的upvote和downvote计数,所以我这样做了
$answer = UpvoteAnswer::find($answerid) ;
$counting = $answer->upvote_answers->count();
echo $counting;
我试图回答一个答案的总计数,但这似乎不起作用,我试图做急切的负载,我怎么能建立这个?
答案 0 :(得分:2)
答案型号:
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();