Read All Child Records

I am stuck into very simple but annoying problem.

If we have db something like this:

User -> Projects -> Tasks

Now if we follow the YII Active Record relations, we’ll have following relations:

User -> ‘hasMany’ => Projects

Project -> ‘belongsTo’ => User

Project -> ‘hasMany’ => Tasks

Task -> ‘belongsTo’ => Project

So this is a common Project and task relationship.

Currently, I am doing:

$Criteria = new CDbCriteria;

$Criteria->with = array(








foreach( User->Project as project ){

	foreach( project->Tasks as task){

		**** list tasks ****



But want to list all the tasks of all the projects, order by TASK DATE, without looping on Project. How can I do that ? I have tried the following but it did not work:

foreach( User->Project->Task as task ){

	*** list tasks ***



I’ve not tried it, but you may be able to set up a HAS_MANY relation to Tasks directly from User, going through your Project relation. You’d be able to set the order in the new relation.

I have no idea if that will work; I’ve never needed to use ‘through’, so it might work differently than I expect.

Hi D3

why didn’t use directly the Task model to get all the Tasks?

In addition if You want to get the related User or Project then load Tasks with Project or User…

Thanks for the reply.

The reason why I want to go through user is that I want to get all the tasks of "that particular" user. So each user has his/her own projects and tasks.


I think what KonApaz was suggesting is that you do something like this:

$criteria = new CDbCriteria;

$criteria->with = 'Project.User';

$criteria->together = true;

$criteria->order = ' ASC';

$tasks = Tasks::model()->findAllByAttributes(array(''=>$userId), $criteria);

That’s pretty much pseudo-code, but it should give you an idea.