eggplantSword's avatar

withCount not working as expected

how come the second line throws an error but not the first one?

        $profiles->with('firstSurveySection.firstSurveyQuestion.surveyQuestionOptions');

        $profiles->withCount('firstSurveySection.firstSurveyQuestion.surveyQuestionOptions');

The error says Call to undefined method App\Models\Tenant\Survey::firstSurveySection.firstSurveyQuestion() but it is since the first line works and returns the correct information.

These are the relationships in the models

//Survey
    public function firstSurveySection()
    {
        return $this->hasOne(SurveySection::class)->where('number', '=', 1);
    }

//SurveySection
    public function firstSurveyQuestion()
    {
        return $this->hasOne(SurveyQuestion::class)->where('number', '=', 1);
    }

//SurveyQuestion
    public function surveyQuestionOptions()
    {
        return $this->hasMany(SurveyQuestionOption::class)->orderBy('number');
    }

What am I doing wrong?

0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
$profiles->with([
    'firstSurveySection' => fn($query) => $query->with([
        'firstSurveyQuestion' => fn($query) => $query->withCount('surveyQuestionOptions')])
]);

$profiles->first()->firstSurveySection->firstSurveyQuestion->surveyQuestionOptions_count

this should do I guess

Please or to participate in this conversation.