简体   繁体   English

Cakephp模型协会

[英]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 = array('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 . 假设您的Classrooms只有一个Teacher ,或Teachers只有一个Classroom ,您甚至可以将Classroom设置为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. 然后,您将通过“老师”找到教室的学生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM