在Yii中加入表格

1 php join inner-join yii

我有两张桌子,tbl_studenttbl_record.我想加入他们,但我不知道如何在Yii中做到这一点.我正在使用php.我找到了教程提及CDbCriteria

'join'=>"INNER JOIN...."
Run Code Online (Sandbox Code Playgroud)

我不知道代码应该具有什么功能以及应该放置代码的型号.tbl_student具有stud_id主键并tbl_record具有record_id主键和stud_id外键.有人可以告诉我一步一步的过程吗?

DCo*_*der 9

不要使用手动连接.使用Active Record可以更轻松地完成此操作.但是,给你整个"一步一步的过程"并没有像你想象的那样让你受益匪浅,你应该自己学习基础知识并提出具体问题.如果这个答案太令人困惑,那么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'),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

第2步:使用Active Record和控制器动作中的关系.这在很大程度上取决于你要做的事情.

示例:使用他/她的所有记录加载单个学生.请注意,我在动作中直接打印数据 - 这是一个坏主意,我在这里使用它只是为了简洁,在实际应用程序中,您将希望使用此数据呈现视图.

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>";
  }
}
Run Code Online (Sandbox Code Playgroud)

这是->with('records')电话的关键部分.它告诉Active Record系统records在查询中包含Student模型的关系数据.活动记录会的ReadL这种关系,它包括在查询返回的结果-对StudentRecords将是可用的$student->records(这将是一个数组).

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

Yii文档中更详细地介绍了Active Record的使用情况:Active Record,Relational Active Record.