0

t know howto accessing data from a related table (with ActiveRecords) and use all those records as a dataSource for a CActiveDataProvider. The main idea is that a user must be able to只使用他的课程中的课程。

我有以下表格:

user (id, name, age, email...),
user_class (user_id, class_id),
class (id, name, description, ...),
course (id, class_id, name, description);

User 和 Class 表具有MANY TO MANY并且 Class 和 Course 表具有ONE TO MANY关系

我还定义了以下关系:

用户模型关系:

'classes'=>array(
    self::MANY_MANY,
    'Class',
    'user_class(user_id, class_id)',
    ),
'courses'=>array(
    self::HAS_MANY,
    'Course',
    array('class_id','id'),
    'through'=>'classes'
)

类模型关系:

'users' => array(
    self::MANY_MANY,
    'User',
    'user_class(class_id, user_id)'
),
'courses' => array(
    self::HAS_MANY,
    'Class',
    'class_id'
),

课程模型关系:

'class' => array(
    self::BELONGS_TO,
    'Class',
    'class_id'
)

在我的CourseController,actionManage()我有这样的东西:

public function actionManage() {
    $currentUser = User::model()->with('classes', 'courses')->findByPk(Yii::app()->user->id);
    $userCourses = $currentUser->classes->courses; //--> NO courses!!!
    /* add users` courses to an CActiveDataProvider //--> how to do this?!
}
4

1 回答 1

0

如果你尝试,var_dump($currentUser->classes);你会注意到它是一个数组。

$userCourses = $currentUser->classes[0]->courses;如果有与相关的类将起作用$currentUser

由于您正在懒惰地加载许多东西(每个“类”在第一次被请求时都会加载其“课程”),这可能会减慢速度,但现在,我猜还是继续吧。

于 2013-04-26T22:27:00.817 回答