Jon Fabian
Jon Fabian

Reputation: 286

Yii CActiveDataProvider Relations

Anyone can enighten me, i am new to Yii. I have 3 tables

projects      (id,name,status,created_by)
users         (id,name)
project_users (id,project_id,user_id)

The condition is: Show all projects if created by current user or current user is a project member. I have already a working code for this.

    $criteria=new CDbCriteria;
    $criteria->join = ' LEFT JOIN project_users pu ON pu.project_id=t.id';
    $criteria->addCondition('created_by='.Yii::app()->user->id.' OR pu.user_id='.Yii::app()->user->id);
    $criteria->distinct = true;

    $dataProvider=new CActiveDataProvider('Project',
    array(
            'pagination'=>array('pageSize'=>15),
            'criteria'=> $criteria
        )
    );

But, id like to learn how can i get same result using "WITH" (relational AR query in Yii). I already tried but all failed. Please help thanks.

Upvotes: 0

Views: 1170

Answers (1)

Telvin Nguyen
Telvin Nguyen

Reputation: 3559

the relation on Project model file

projectUsers' => array(self::HAS_MANY, 'ProjectUsers', array('id'=>'project_id')),

$dataprovider should be

$dataProvider=new CActiveDataProvider('Project',
        array(
                'pagination'=>array('pageSize'=>15),
                'criteria'=>array(
                    'with'=>array(
                        'projectUsers' => array('alias' => 'pu')
                    ),
                    'condition' => 't.created_by='.Yii::app()->user->id.' OR pu.user_id='.Yii::app()->user->id,
                    'distinct'=>true,
                    'together'=>true, 
                ),
            )
        );

Check out my picture. The criteria is more powerful than that, but you can understand the basically how to use

enter image description here

Small tip: If everything is new with you, just enable Yii log to see what the query is produced eventually, then you can troubleshoot the problem by yourself.

Upvotes: 2

Related Questions