It is sometimes desirable to store additional data with a many to many association. Consider the following
Student hasAndBelongsToMany Course
Course hasAndBelongsToMany Student
In other words, a Student can take many Courses and a Course can be taken by many Students. This is a simple many to many association demanding a table such as this:
id | student_id | course_id
Now what if we want to store the number of days that were attended by the student on the course and their final grade? The table we'd want would be:
id | student_id | course_id | days_attended | grade
The trouble is, hasAndBelongsToMany will not support this type of scenario because when hasAndBelongsToMany associations are saved, the association is deleted first. You would lose the extra data in the columns as it is not replaced in the new insert.
The way to implement our requirement is to use a join model, otherwise known as a hasMany throughassociation. That is, the association is a model itself. So, we can create a new model CourseMembership. Take a look at the following models.:
On Monday, 28 May 2012 12:35:06 UTC-4, Ratty wrote:
You can have extra fields with no problem at all. If you look at the
models, both your user and survey model will have the join table
(users_surveys) defined with the key that it is joined on.
All you will have to do is generate a model for users_surveys too so
that you can extract the extra data and provide queries to use both
user_id and survey_id instead of the id field of the join table.
Basically, it is quite straightforward to do this, but Cake will not
generate all the code for you.
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php
No comments:
Post a Comment