Reputation: 2148
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
Upvotes: 2
Views: 1853
Reputation: 2148
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');
}
}
Upvotes: 2