I am trying to count related tables via model but can't successful.
I have a categories, questions and answers table.
I can count questions related to a category but can't count answers from related categories. U can think its a forum system.
Category Model
public function questions(){
return $this->hasMany('App\Question','category_id','id');
}
Question Model
public function answer()
{
return $this->hasMany('App\Answer');
}
public function category()
{
return $this->belongsTo('App\Category','category_id','id');
}
Answer model
public function question()
{
return $this->belongsTo('App\Question','question_id','id');
}
I can count questions for a related category view Category model like below
public function questioncount(){
return $this->questions()->where('status',1)->count();
}
Tried below for counting answers but no luck;
public function answercount()
{
return $this->questions()
->leftJoin('answers','answers.question_id','=','questions.id')
->count();
}
You might try Has Many Through relationship.
So let's define a Has Many Through relationship in Category model:
class Category
{
public function answers()
{
return $this->hasManyThrough(Answer::class, Question::class);
}
}
Then of course you can get the answers count like this:
$question->answers()->count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With