1
votes

I have a question which seems is repeated but it's not:

I explain with a small example.

I have two table: Students & courses.

Each Student can take N courses and each course can be taken by N students.

I want to have access the courses by Students and also have access to Students by courses.

EX:

1- Give me the list of courses that Student with id=1 took.

2- Give me the list of Students who took the Course with id=2000.

If I use belongsToMany in StudentsTable Class is enough or I should Also define hasMany or belongsToMany in CoursesTable class.

Tell me what should I do.

Thank in advance.

PS: I use CakePHP 3.x

1
Go with hasMany Through.I recommend to visit the official site of Cakephp. They have provided a great example in book.cakephp.org/2.0/en/models/…Agam Banga
You are right to use the HABTM relationship. You need a third table that will join students to courses and visa versa. Cakes convention wants you to have students table, courses table and the connecting table labelled students_courses, but really you can name it whatever you want. I usually go with something easy to understand like student_course_links. students_courses should contain its own primary key and the foreign keys for both students and courses. I feel like the documentation is good enough, but if you need me to explain more i will tryJason Joslin
@Agam Banga, Thanks for the link but it's for CakePHP 2.x.Malus Jan
@MalusJan Cake 3 also has this document book.cakephp.org/3.0/en/orm/…Agam Banga
@MalusJan you need to bake the models for all three in case of HasMany through.Agam Banga

1 Answers

1
votes

As Agam Banga said in this link we should use:

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');
    }
}