开发者

Cakephp model association

I am trying to figure out which relationship type should I use to relate the following:

We have a classroom that has a teacher and students.

Students and teacher belongsTo classroom. But what about the other way around?

Can I use the following in the Classroom model:

var $hasMany = array('Students');

var $hasOne = arra开发者_JAVA技巧y('Teacher');

Thanks.


Depends on how you want to retrieve and/or model the data.

Assuming your Classrooms will only have one Teacher, or Teachers will only have one Classroom, you can even get away with making Classroom a field of Teacher.

But we'll assume you want to keep it all abstracted from each other. In this case, your models would look something like this:

// classroom.php
class Classroom extends AppModel {
    var $hasMany = array( 'Student' );
    var $hasAndBelongsToMany = array( 'Teacher' );
}

// teacher.php
class Teacher extends AppModel {
    var $hasMany = array( 'Student' );
    var $hasAndBelongsToMany = array( 'Classroom' );
}

// student.php
class Student extends AppModel {
    var $belongsTo = array( 'Teacher', 'Classroom' );
}


Its very dependent on your situation but at my old school that would indeed be correct though maybe an unnecessary relationship to add.

Teacher has many students Classroom has one teacher Classroom has many students

However, do the students move around? Is the relationship between students and classroom entirely necessary? I would think the most defining relationship in this instance is the teacher-student one. Then perhaps the teacher-classroom. You can surmise based on those relationships that some students are part of a classroom.

Therefore:

Classroom - Teacher -< Students Classroom (has one) Teacher (has many) Students

You would then find the students of a classroom via the Teacher.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜