0

我有这个表:

Careeer { id(pk) , name}
Student { email (pk), ...}
Career_Student { student_email(pk)(fk), career_id (pk)(fk), semester }

在我的 Yii 模型中,我有这种关系

'careers' => array(self::MANY_MANY, 'Career', 'Career_Student(student_email, career_id)')

最后我有这个查询

$criteria = new CDbCriteria();
$params = array (':email' => $_SESSION['USER']);
$criteria->addCondition("email=:email");
$criteria->params = $params;
$result = Student::model()->find($criteria);
$careers=$result->careers;

我的问题是 Yii 没有在我的 $careers 变量中检索“学期”列。

我怎样才能做到这一点?

先感谢您!

4

1 回答 1

0

您可以将关系表示为与选项相关MANY_MANY的两个关系的组合:HAS_MANYthrough

'career_student' => array(self::HAS_MANY,'Carrer_Student','student_email'),
'careers' => array(self::HAS_MANY,'Career', 'career_id','through'=>'career_student'),

还要确保careerCareer_Student模型中定义关系:

'career' => array(self::BELONGS_TO, 'Career', 'career_id'),

现在,当您查询学生时with('careers'),两个关系都将被填充:

$criteria->with = 'carreers';
$result = Student::model()->findAll($criteria);
foreach($student->career_student as $careerStudent) {
    // You have access to the bridge table ...
    echo $careerStudent->semester;

    // ... and the connected career table
    echo $careerStudent->career->name;
}
于 2013-07-14T09:17:30.447 回答