Question

I'm gonna use the CourseMembership example from the CakePHP manual to illustrate my question. So there are the following tables:

CREATE TABLE course ( id INT NOT NULL PRIMARY KEY, course_name VARCHAR(255) ); CREATE TABLE student ( id INT NOT NULL PRIMARY KEY, student_name VARCHAR(255) ); CREATE TABLE course_membership ( course_id INT NOT NULL REFERENCES(course.id), student_id INT NOT NULL REFERENCES(student.id), attended_lectures TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (course_id, student_id) );

My models look like this:

class Course extends AppModel {
    public $hasMany = array('CourseMembership');
}
class Student extends AppModel {
    public $hasMany = array('CourseMembership');
}
class CourseMembership extends AppModel {
    public $belongsTo = array('Course', 'Student');
}

What is the best way to add a CourseMembershipProperty model/table to this setup? I'm curious about both the schema and the relationship configuration in the model class.

The relationships should be:

  • CourseMembershipProperty belongsTo CourseMembership
  • CourseMembership hasMany CourseMembershipProperty.

For simplicity's sake, the CourseMembershipProperty model's table can have two VARCHAR fields, name and value.

Was it helpful?

Solution

There are a few issues:

Your table names should be pluralized:

course should be courses

student should be students

course_membership should be course_memberships

Note this section from the CakePHP cookbook:

http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

"CakePHP does not support composite primary keys."

The course_memberships table should have a primary key of id that auto increments and the composite primary keys of course_id and student_id should be removed and be utilized as foreign keys. Without first correcting this problem, the CourseMembership model will misbehave.

After that, the CourseMembershipProperty model should link to the CourseMembership model by using a foreign key of course_membership_id. This should work by simply defining the Models as you have in your example since we will be following the CakePHP naming conventions at this point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top