我不只是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
CRUD`他班上的课程。
我有以下表格:
user (id, name, age, email...),
user_class (user_id, class_id),
class (id, name, description, ...),
course (id, class_id, name, description);
用户和班级表格 MANY TO MANY ,班级和课程表格 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?!
}
答案 0 :(得分:0)
如果您尝试var_dump($currentUser->classes);
,您会注意到它是一个数组。
$userCourses = $currentUser->classes[0]->courses;
相关联的类,则 $currentUser
将起作用
由于你懒得加载很多东西(每个“课程”在第一次被要求时加载它们的“课程”)这可能会变得缓慢,但是现在,我想用它来运行。