views:

40

answers:

2

Hi

In my app I have 2 tables that have a many to many relationship. Let us say these are table students and table courses. Each course can have many students and each student can also enroll in many courses.

Now I want to create a associative table which according to cakephp should be named courses_students.

However for various reasons I wish to name the new table as enrollments. I would be using the primary key of the this table at a lot of places and would rather use enrollment_id than courses_student_id as the foreign key.

If I do this would I have to do a lot of manual coding or can I still use the automagic of cakephp? Any pointers on best practices/guidelines regarding this issue?

Thanks

A: 

I have never thought about this, before but maybe you could name the primary key enrollment_id and keep the table named courses_students and bake it. I think you can set the primary key and id of the model like so:

var $id = 'enrollment_id';
var $primaryKey = 'enrollment_id'

Hope that helps.

jimiyash
+4  A: 

The short answer is yes. If a joining table has its own ID alongside the 2 foreign keys, Cake can still work its hasAndBelongsToMany magic.

What I would do, possibly at the risk of YAGNI, is forego the hasAndBelongsToMany association in favor of two hasMany relationships. Since you plan to access each enrollment by its own ID already, I would anticipate that, at some point, it may have properties of its own (e.g. enrollment_date, course_evaluation, etc.) and may need get treated as a separate model all together. The Enrollment model, of course, would belongsTo the Student and Course models.

Obviously the "what I would do" scenario was unsolicited, but I thought I'd offer a slightly different direction that still allows for a healthy dose of Cake magic as well as a bit of extensibility that may come into play for you based on what you're already doing.

Rob Wilkerson
Rob, the "what I would do" scenario is hugely appreciated - in fact, much more than the "short answer" because it includes "wisdom" in addition to "information". I shall try out the solution and then revert. And you are spot on with the observation that the enrollments table would have properties of its own. :-)
Vinayak
Brilliant answer Rob Wilkerson. That is what made me think twice as to why I am insisting on implementing HABTM relationship? The enrollments has it's own properties (this statement cleared all the doubts). Thanks for your answer it helped me too. :-)
Gaurav Sharma
Glad it helped. My own approach has been that as soon as my join table stops being a simple join table (two columns, dual primary key, both keys are also foreign keys) then it's time to treat it as its own model and drop any HABTM efforts.
Rob Wilkerson