Laravel Count Multiple Tables In Eloquent

Viewed 1023

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();
}
2 Answers

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 want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:

 $answers = App\Question::withCount('answers')->get();

Related