Question

I am new to yii. I have three models models

 Site(id,name)
 User(id,name,..)
 UserSite(id,user_id,site_id)

What i need is when im selecting a dropdown of site I need to users belongs to that site

the relation in User model is 'userSites' => array(self::BELONGS_TO, 'UserSite', 'id'),

And the search function User model is,

public function search($sid)
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('customer_id',$this->customer_id,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('company',$this->company,true);
        $criteria->compare('country',$this->country,true);
        $criteria->compare('date_added',$this->date_added,true);
                $criteria->compare('expiry_date',$this->expiry_date,true);
                if($sid!=null)
                {
                    $criteria->with = array('userSites'); 
                    $criteria->addCondition('userSites.site_id='.$sid);
                }

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,

        ));
    }

Here what happenning is displaying users like (user.id=user_site.id) but actually i need (user.id=user_site.user_id).

Now this relation 'userSites' => array(self::BELONGS_TO, 'UserSite', 'id'),returns UserSite->id what i need it has to return UserSite->User_id

Please Somebody help me to solve this problem..

Was it helpful?

Solution

Your relation is inverted. Each User can have many UserSites therfore your relation should be

'userSites' => array(self::HAS_MANY, 'UserSite', 'user_id')

To eager load relations in CActiveDataProvider you have to set CDbCriteria::together to true:

if($sid!=null){
    $criteria->together = true;
    ...

An explanation for this is given at http://www.yiiframework.com/wiki/280/1-n-relations-sometimes-require-cdbcriteria-together/

But tracing the application's queries shows that when CActiveDataProvider gets data, it handles 1:n related tables a bit different. AR gets the data from the parent table and 1:1 related child tables with one query joining all those 1:1 child tables. 1:n child tables are not part of this query. AR gets data from those with subsequent queries, one query per 1:n child table, specifying the rows it wants with a WHERE PK IN (id1, id2, ...) clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top