Search code examples
yiimany-to-manyrelational

Yii Many to Many Relational Query


Using a many many relational query with users having many clients and clients having many users. Trying to view a record of a particular client for a particular user. And if that client is not associated with that user, redirect to a different page.

// the relation in the client model
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
                'owners'=>array(self::MANY_MANY, 'User','owner_client(owner_id, client_id)'),
                    );
}

//the relation in the user model
public function relations()
{


    return array(

        'clients'=>array(self::MANY_MANY, 'Clients','owner_client(owner_id, client_id)'),
    );
}

//determine if user can view this client
//client record
        $client_record = Clients::model()->findByPk($id);
        //many query to find users
        $users =  $client_record->owners;

        //if user id is not found in array, redirect
        if (!in_array(Yii::app()->user->id, $users)) 
        {
           $this->redirect(array('/site/dashboard')); 
        }

The above code redirects, even though I know the client is related to the user logged in


Solution

  • When you call $users = $client_record->owners;, what you're getting back is an array of all your user models that are associated with the current client. As a result, you're comparing integers to objects, which means your in_array() condition will always fail.

    What I recommend is that you build a conditional query to do your verification check. Something like this should work:

    $model = Clients::model()->with(
        array(
            'owners'=>array(
                'select'=>'owner_id',
                'condition'=>'user.id = '.Yii::app()->user->id,
            ),
        )
    )->findByPk($id);
    
    if ($model === null) {
        $this->redirect(array('/site/dashboard')); 
    }