Relational access

I have 3 tables

User(id, name…)

Has many

Courses(id, name…)

Has many

parts (id, name…)

I know I can access course like this

$model=User::model()->findByPk($id);

$course = $model->courses (as I have relation with the name ‘courses’ in my model)

But what about If i want to access parts under that courses

$parts = $model->courses->parts ;

I know Its not working but how to achieve this ? as I want to access parts under that course under that user

$model->courses will return an array of Course, so to get the array of Parts from the first course you should use $model->courses[0]->parts

It really should be:

User

Course

Part

Notice: not plural!

Then the User model has $courses and Course has $parts.

Then just:


foreach ($users as $user) {

	foreach ($user->courses as $course) {

    	foreach($course->parts as $part) {

        	echo $part->name . '<br/>';

}

}

}

Written off the cuff, but you get the idea.

Thanks for the useful info.

Still I have one confusion

I have many to many relation between user and course tables (having third table for this user_course)

so If I want to check whether a user register in a course then what is the best method to do it using yii

Can I do something like this isset($course->users->findByPk($userId)) ?

In this case what I normally do is create a model to this user_course table and use:




$userCourse = UserCourse::model()->findByAttributes(array(

  'userId'=>$userId,

  'courseId'=>$courseId,

));

if ($userCourse != null)

  echo 'User registered';

else

  echo 'User not registered';