我有两张桌子,tbl_student和tbl_record。我想加入他们,但我不知道该怎么做。我用的是php。我发现一些教程提到了CDbCriteria和
'join'=>"INNER JOIN...."我不知道代码应该在什么功能中,代码应该放在什么模型中。tbl_student有stud_id主键,tbl_record有record_id主键,stud_id作为外键。有人能告诉我一步一步的过程吗?
发布于 2012-04-28 10:58:34
不要使用手动连接。使用活动记录可以更容易地做到这一点。但是,给你整个“一步一步”的过程并不像你想的那样对你有好处,你应该自己学习基础知识,并提出具体的问题。如果这个答案太混乱,那么Alfredo是对的,在继续之前,您应该花更多的时间学习这个框架。
步骤1:在各自的模型中指定表关系。如果数据库模式使用外键(绝对应该使用外键),那么gii模型生成器可以自动确定这些密钥,否则需要手动声明它们:
/**
* @property Record[] $records
*/
class Student extends CActiveRecord {
// other code...
public function relations() {
return array(
// other relations
array('records', self::HAS_MANY, 'Record', 'stud_id'),
);
}
}
/**
* @property Student $student
*/
class Record extends CActiveRecord {
// other code...
public function relations() {
return array(
// other relations
array('student', self::BELONGS_TO, 'Student', 'stud_id'),
);
}
}步骤2:使用活动记录和控制器操作中的关系。这在很大程度上取决于你想做什么。
例句:把他/她的所有记录加载到一个学生身上。请注意,我在操作中直接打印数据--这是个坏主意,我在这里使用它只是为了简洁,在一个实际的应用程序中,您将希望用这些数据呈现一个视图。
public function actionStudentInfo($id) {
$student = Student::model()->with('records')->findByPk($id);
if(!$student) {
throw new CHttpException(404, "Student not found!");
}
echo "<h2>Found the requested student with details:</h2>",
"<pre>", htmlspecialchars(print_r($student->attributes, true)), "</pre>";
if(count($student->records)) {
echo "<h3>Student records:</h3>", "<ul>";
foreach($student->records as $record) {
echo "<li><pre>", htmlspecialchars(print_r($record->attributes, true)), "</pre></li>";
}
echo "</ul>";
} else {
echo "<p>Student has no records...</p>";
}
}其中的关键部分是->with('records')调用。它告诉活动记录系统在查询中包含学生模型的records关系数据。活动记录将重新读取该关系,并将其包含在查询和返回的结果中--Student的Records将在$student->records中可用(这将是一个数组)。
您可以在关系规范中包含许多额外的细节,例如,现在它将以不特定的顺序获取这些记录,如果要强制排序,可以指定'order' => 'field_name ASC'。
https://stackoverflow.com/questions/10362488
复制相似问题