Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Count Multiple Tables In Eloquent

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();
}
like image 404
sadri Avatar asked Nov 24 '25 21:11

sadri


1 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();
like image 192
Kevin Bui Avatar answered Nov 27 '25 22:11

Kevin Bui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!