Changing foreach loop into CActiveDataProvider

Hi folks,

I have the following tables:

  • event

  • event_user

  • group

  • group_user

  • user

It’s a little untraditional in that Groups are invited to Events rather than inviting specific users. Thus, each User MANY_MANY Groups and each Group HAS MANY Events. For example, a user could belong to 3 groups, each group has 4 of their own events, so the user should be able to see those 12 events.

Currently, to see the events available to the current user, I use a for loop.

$mygroups = Yii::app()->user->model->groups; //Get's the current user's model, and then their groups

$mygroupsevents = array();


foreach($mygroups as $group) {

	$mygroupsevents = array_merge($mygroupsevents, $group->events);


$this->render('events', array(



However, I would rather load this data via a CActiveDataProvider so that I can feed it into the various widgets. Does anyone have a more graceful solution for me?


You can try to add a inCondition:

$model=new Event('search');

$model->unsetAttributes();  // clear any default values



$dataProvider= $model->search();

$dataProvider->criteria->addCondition("id IN (SELECT evenId FROM event_for_groups WHERE group_id IN (SELECT group_id FROM user_in_groups WHERE userId='$userId'))");

$this->render('events', array(




Thank you so much! That worked perfectly, I had to alter the search call for my table names like so (for future readers with a similar problem):

$dataProvider->criteria->addCondition("id IN (SELECT id FROM event WHERE groupId IN (SELECT groupId FROM group_user WHERE userId='$userId'))");

I will have to learn more about this cool search function.