Yii关系不正常(Yii 1.x)

时间:2015-01-23 12:17:55

标签: database yii frameworks relational-database

我有两个模型如下:

MyuserClassroom - db table is called 'myuser_classrooms'
MyuserClassroomPivot - db table is called 'myuser_classrooms_pivot'

结构非常简单

myuser_classrooms(classroom_id, title, organisation_id, active)
myuser_classrooms_pivot(classroom_id, user_id)

数据透视表中的教室ID是外键(与users表的user_id一样)

在MyuserClassroom模型中,我有以下关系

function relations() {
   return array(
      'classroomStudents' => array(self::MANY_MANY, 'MyuserClassroomPivot', 'myuser_classrooms_pivot(classroom_id, user_id)')
   )
}

我只想通过classroom_id来获取数据透视表中所有行的集合,但它对我来说不起作用,因为我得到一个空数组。

任何人都可以建议我做错了吗?

这是数据库的sql小提琴 http://sqlfiddle.com/#!2/37121f/1

//下面是Yii在查询日志中生成的查询..

SELECT
`classroomStudents`.`classroom_id` AS `t1_c0`,
`classroomStudents`.`user_id` AS `t1_c1`
 FROM
`myuser_classrooms_pivot` `classroomStudents`
  INNER JOIN `myuser_classrooms_pivot` `classroomStudents_classroomStudents`   ON (
`classroomStudents_classroomStudents`.`classroom_id` = 4
)
 AND (
`classroomStudents`.`classroom_id` = `classroomStudents_classroomStudents`.`user_id` )

1 个答案:

答案 0 :(得分:0)

UserMyuserClassroom表之间存在多对多关系。但是MyuserClassroomMyuserClassroomPivot表之间有很多关系。

因此,如果您想从数据透视表中获取行,请写:

public function relations()
{
    return array(
        'pivots'=>array(self::HAS_MANY, 'MyuserClassroomPivot', 'classroom_id'),
    );
}

注意,在这种情况下,您应该为MyuserClassroomPivot表创建myuser_classrooms_pivot ActiveRecord类。