Safe Way For Retrieving Objects

Hello

I’m wandering what the best solution is for the following.

Let’s say I’m only allowed to get a User which is linked to my account




function getUser($user_id)

{

 $u = User::model()->findByPk($user_id);

 if ($u->account_id == $this->account->id)

 {

   ..

 }

}



I would like to do something as below




function getUser($user_id)

{

 $u = $this->account->users->findByPk($user_id)

 if (!$u) {throw bla bla}

}




Is something like this possible in Yii?


function getUser()

{

 $u = User::model()->findByPk($this->account->id);


}

Now I receive the user with id: account_id, thats not the intention i think




$u = User::module()->findByAttributes(array('id'=>$user_id, 'account_id'=>$this->account->id));



Thanks for the reply. However it’s not really what I hoped for. Problem is that the findByAttributes syntax is quite more complicated and limited for this purpose. I’m affraid I want something which is not possible (yet).

I don’t want to put the account_id condition in the where statement manually. The notation below is much shorter and safer




$this->account->users->findByPk($user_id)



So try this:




$u = $this->account->users(array('condition'=>'id=:id','params'=>array(':id'=>$user_id)));

$u = reset($u); // since $u will be an array with zero or one element, test $u for false to see if found



If you really want to use the …ByPk notation, you probably should create your own method in the CActiveRecord class or override the getRelated() method, see the API docs and source for more info.