0
votes

I'm creating a basic student/course script. I have 3 models I'm working with: Student, Course, StudentCourse. Below are the relationships:

Student:

  • 'hasMany' Course
  • 'hasMany' StudentCourse

Course:

  • 'belongsTo' Student (This is the course INSTRUCTOR)
  • 'hasMany' StudentCourse
  • 'hasAndBelongsToMany' Student (these are the students signed up for the course)

StudentCourse:

  • 'belongsTo' Student
  • 'belongsTo' Course

Now, I'm running into some problems when I'm trying to get all of the students who have signed up for a course (because it's also returning the instructor for the course and messing up the array). How can I make it so that the "belongsTo" in "Course" uses an alias called "Instructor" (this way when I get data for a "Course", I have: $course['Course'](course data), $course['Instructor'](instructor's data, referenced by student_id in the courses table) and $course['Students'](students signed up for course)?

Here are the controllers/the view call: http://bin.cakephp.org/view/645421766

1

1 Answers

3
votes

I think you should indeed change your schema around a little. Students and Instructors are both Users. So make a User model with id, name, email password, etc. I suggest adding an additional model called Participant or CourseParticipant. So, Course hasMany Participant. Your Participant model has course_id, user_id, 'as' or 'role' (student, instructor, etc).

Using the Course hasMany Participant you can do:

array(

'Student' => array(
    'className' => 'Participant',
    'conditions' => array('Student.as' => 'student')
)

);

...same for Instructor. See the conditions and use of the 'as' field? I don't recommend habtm for this (I never recommend cake habtm...and I think you're on the right track with StudentCource).

Let stories guide your schema. Users can be Students and Instructors. Courses have Users who Participate as Students or Instructors. Some day you might have Users who participates in a Course as an Assistant.

Now you have all sorts of interesting data. Courses this Instructor has taught. Courses this Student has taken.

*edit: I should add that cake convention suggests your Participant class be named CourseUser.