How to make a query that can count in a contain table

I have a query code in my view controller

     $teacher = $this->Teachers->get($id, [
            'contain' => ['Users', 'QuestionCourses' => 
            function($s){
                return $s->contain(['Courses', 'Questions']);
            }
            , 'TeacherCourses' => 
            function($q){
                return $q->contain(['Courses', 'Levels']);
            }]
        ]);

        $this->set('teacher', $teacher);

in this case what I want is just only count data form questions table, in table questions have a foreign key called questioncourse_id
anyone can help me to correct my code, please?

thank you

have you thought about using subqueries and ->join( …)
the subquery, provides countdata based on your keyfields.

$subquery: fetching countdata and fields to link
$query: joins the subquery plus all keyfields
add needed contains to it and check also enableAutoFields(true);

ps: you dont need a function for deeper associations or ? … you can either use just => […] or you use Dot-Notation. like QuestionCourses.Courses, QUestionCourses.QUestions. but check also your associations in your entity model for such cases usually you use the “through” link. - check the docs :slight_smile:

sorry for “flat” reply, but maybe I update you with some real examples.