数据库
classe表:
CREATE TABLE `classe` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`cname` varchar(10) DEFAULT NULL,
`tid` int(11) DEFAULT NULL,
PRIMARY KEY (`cid`),
KEY `FK_ID_CLASS` (`tid`),
CONSTRAINT `FK_ID_CLASS` FOREIGN KEY (`tid`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8;
student表:
CREATE TABLE `student` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`sname` varchar(10) DEFAULT NULL,
`cid` int(11) DEFAULT NULL,
PRIMARY KEY (`sid`),
KEY `FK_ID` (`cid`),
CONSTRAINT `FK_ID` FOREIGN KEY (`cid`) REFERENCES `classe` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
teacher表:
CREATE TABLE `teacher` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`tname` varchar(10) DEFAULT NULL,
PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
使用gii生成相应的model模型
一对多:hasMany(),第一个参数为class的全名(app\models\Student),第二个参数为两个表中对应的字段
一个classe对应多个student
public function getStudents() { $students = self::hasMany(Student::className(), ['cid' => 'cid']); return $students; }
一个teacher对应多个classe
public function getClasses() { return $this->hasMany(Classe::className(), ['tid' => 'tid']); }
一对一:hasOne(),参数同hasMany()方法
一个classe只对应一个教师
public function getT() { return $this->hasOne(Teacher::className(), ['tid' => 'tid']); }一个学生对应一个Classepublic function getClasse() { return $this->hasOne(Classe::className(), ['$cid' => 'cid']); }controller代码:</pre><br /><pre name="code" class="php"><span style="white-space:pre"> </span>// 查询班级内所有学生 public function actionQueryStudentForCid() { $cid = Yii::$app->request->get('cid'); $classe = Classe::findOne($cid); // $studnets = $classe->getStudents()->asArray()->all(); // $studnets = $classe->students; $studnets = $classe->getStudents(); // echo "<pre>"; // var_dump($studnets); // echo "</pre>"; $dataProvider = new ActiveDataProvider([ 'query' => $studnets, 'pagination' => [ 'pagesize' => '10' ] ]); $data = [ 'flag' => 'stu', 'title' => $cid.'号班级内所有学生', 'dataProvider' => $dataProvider ]; return $this->render('index', $data); } // 查询教师管理的班级 public function actionQueryClasseForTid() { $tid = Yii::$app->request->get('tid'); $teacher = Teacher::findOne($tid); // $studnets = $classe->getStudents()->asArray()->all(); $classes = $teacher->getClasses(); // echo "<pre>"; // var_dump($studnets); // echo "</pre>"; $dataProvider = new ActiveDataProvider([ 'query' => $classes, 'pagination' => [ 'pagesize' => '10' ] ]); $data = [ 'flag' => 'cla', 'title' => $tid.'号教师管理的班级', 'dataProvider' => $dataProvider ]; return $this->render('index', $data); }