How to use belongsToMany through

I want to use the “through” option to have the ability to filter data on a join table.
So I took the example of the book CakePHP v3.

class StudentsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Courses', [
            'through' => 'CourseMemberships',
        ]);
    }
}

class CoursesTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Students', [
            'through' => 'CourseMemberships',
        ]);
    }
}

class CoursesMembershipsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Students');
        $this->belongsTo('Courses');
    }
}

How should I construct the query to find Courses for given Student that he has Grade == “A” for example ?

If i use this

$query = $this->Courses->find('all')
    ->contain(['CourseMemberships'])
    ->where(['CourseMemberships.student_id' => $student['id'], 'CourseMemberships.grade' => 'A']);

This will not work. I get an error indicating that I was no association “CourseMemberships” with the tables “Courses” O_o

Do I filter on “_joinData” ?

Thank you for your help,

Wheezy

Hi.you must determind foreignKey ,targetForiegnKey , joinTable in your model .for example $this->belongsToMany('Contests', [ 'foreignKey' => 'design_id', 'targetForeignKey' => 'contest_id', 'joinTable' => 'contests_designs' ]);