CakePHP 3.x - hasMany through association - find

后端 未结 2 1850
刺人心
刺人心 2020-12-30 16:39

Assuming I have exactly the setup as in CookBook here: http://book.cakephp.org/3.0/en/orm/associations.html

class StudentsTable extends Table
{
    public fu         


        
2条回答
  •  [愿得一人]
    2020-12-30 17:10

    through Allows you to provide a either the name of the Table instance you want used on the join table, or the instance itself. This makes customizing the join table keys possible, and allows you to customize the behavior of the pivot table.

    Define a more specific relationship using array syntax:

    class StudentsTable extends Table
    {
    
        public function initialize(array $config)
        {
            $this->belongsToMany('Courses', [
                'joinTable' => 'courses',
                'through' => 'CourseMemberships',
            ]);
        }
    }
    
    class CoursesTable extends Table
    {
    
        public function initialize(array $config)
        {
            $this->belongsToMany('Students', [
                'joinTable' => 'students',
                'through' => 'CourseMemberships',
            ]);
        }
    }
    
    class CoursesMembershipsTable extends Table
    {
    
        public function initialize(array $config)
        {
            $this->belongsTo('Students', [
                'foreignKey' => 'student_id',
                'joinType' => 'INNER',        // OR specify the type 
            ]);
            $this->belongsTo('Courses', [
                'foreignKey' => 'course_id',
                'joinType' => 'INNER',
            ]);
        }
    }
    

    Be sure that you have tables courses, students, and course_memberships.

    Now run the code:

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

    Well, I'm affraid if you really need something related with the HasMany Associations.

提交回复
热议问题