在 Yii 中连接表


Joining tables in Yii

>我有两个表,tbl_studenttbl_record。我想加入他们,但我不知道如何在 Yii 中做到这一点。我正在使用 php。我发现教程提到了CDbCriteria

'join'=>"INNER JOIN...."
我不知道代码应该

是什么功能,代码应该放在什么模型上。 tbl_student具有stud_id主键,tbl_record具有record_id主键和外键stud_id。有人可以告诉我分步过程吗?

不要使用手动联接。使用活动记录可以更轻松地完成此操作。但是给你整个"一步一步的过程"并不像你想象的那么多,你应该自己学习基础知识并提出具体的问题。如果这个答案太令人困惑,那么 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关系数据。活动记录将读取该关系并将其包含在查询和返回的结果中 - StudentRecords将在$student->records中可用(这将是一个数组)。

您可以在关系规范中包含很多额外的详细信息,例如,现在它将以没有特定顺序获取这些记录,如果要强制执行排序,可以指定'order' => 'field_name ASC'

活动记录的使用在 Yii 文档中有更详细的介绍:活动记录、关系活动记录。