如何从数据库中提取复杂结果-Yii

如何从数据库中提取复杂结果-Yii,yii,Yii,我面临使用Yii关系从表中取出记录的问题 我有三张桌子 1) 学生->身份证、姓名、卷号 2) 主题->ID,名称 3) 学生学习科目->ID,学生ID,科目ID 假设有多个学生选修了多个科目,这些科目存储在第三个表“学生选修科目”中,那么我如何获取选修任何特定科目的学生列表 e、 g.学习数学的学生名单 下面哪一个关系是正确的,如何将结果输入$dataProvider变量 'Students'=>array(self::HAS_MANY, 'Subjects', 'Student_ID'

我面临使用Yii关系从表中取出记录的问题

我有三张桌子

1) 学生->身份证、姓名、卷号

2) 主题->ID,名称

3) 学生学习科目->ID,学生ID,科目ID

假设有多个学生选修了多个科目,这些科目存储在第三个表“学生选修科目”中,那么我如何获取选修任何特定科目的学生列表

e、 g.学习数学的学生名单

下面哪一个关系是正确的,如何将结果输入$dataProvider变量

'Students'=>array(self::HAS_MANY, 'Subjects', 'Student_ID'),


科目和学生之间的关系很多,但你写得有点错,这就是你需要的:

class Subjects extends CActiveRecord
{
    // ...
    public function relations()
    {
        return array(
            'Students'=>array(self::MANY_MANY, 'Students', 'Students_taken_Subjects(Subject_ID, Student_ID)'),
        );
    }
    // ...
}
编写完此关系后,Subjects活动记录将具有一个Students属性,该属性返回一个数组,其中0个或多个学生学习该主题。您可以这样访问它们:

$subject = Subjects::model()->findByPk($pk);
$students = $subject->Students;  // an array with the subject's students
$subjects = Subjects::model()->with('Students')->findAll();
$subjects[0]->Students;
$subjects[1]->Students;
// ...
上述代码将导致两个DB访问,一个用于$subject,另一个用于相关的$student。这可能很好,但如果您访问了很多主题,那么可能会出现“延迟加载”过多的问题。你可以告诉Yii“急切地加载”学生和以下科目:

$subject = Subjects::model()->findByPk($pk);
$students = $subject->Students;  // an array with the subject's students
$subjects = Subjects::model()->with('Students')->findAll();
$subjects[0]->Students;
$subjects[1]->Students;
// ...
在这里,您可以找到所有的主题,但是提醒Yii——与('Students')一起使用——您也需要每个主题的学生信息。这可以确保与你找到的科目相关的所有学生都会立即被抓获。
with()
函数的替代方法是使用标准的
with
属性:

$criteria=new CDbCriteria;
$criteria->with = array('Students');
$subjects = Subjects::model()->findAll($criteria);
无论哪种方式,当你要求一个科目的学生这样做:

$subject = Subjects::model()->findByPk($pk);
$students = $subject->Students;  // an array with the subject's students
$subjects = Subjects::model()->with('Students')->findAll();
$subjects[0]->Students;
$subjects[1]->Students;
// ...
您不会每次都收到另一个DB调用,因为Yii已经加载了数据

在我给出更多细节之前,你需要提供更多关于你想对数据提供者中的学生做什么的细节