How To Access Relation Data In Any View

I’ve a relation like below… how can i access this join relation data through out my site…using


Yii::app->user->organisations or Yii::app->benefitUses

the following is my relation and it is generated by gii…

this is my relation for User 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(

	'benefitUses' => array(self::HAS_MANY, 'BenefitUse', 'user_id'),

	'organisations' => array(self::MANY_MANY, 'Organisation', 'user_organisation(user_id, organisation_id)'),				

			

	}

when i’m accessing like this


<?php var_dump(Yii::app()->user->benefitUses);die; ?>

from view it is showing error like "Property "CWebUser.benefitUses" is not defined."[/code]

And

when i’m accessing like this


<?php var_dump($this->user->benefitUses);die; ?>

from view it is showing error like "Property "UserController.user" is not defined."[/code]

how to get the user instance here rather than CWebUser or UserController?? and how can i access the joining data all over site with


Yii::app->user->organisations or Yii::app->benefitUses

Any help pls…

Many Thanks,

Personally, I’d extend CWebUser, like so:




<?php


class WebUser extends CWebUser

{

    private $_model;


    public function getModel()

    {

        if ($this->_model === null)

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


        return $this->_model;

    }

}



With updated config:




    'user'=>array(

        'class'=>'WebUser',

        ....

    ),



Then you can access any of your user relations:




Yii::app()->user->model->benefitUses;



It uses lazy loading of the user record, so it will only hit the database if you access the model, and will store it for the remainder of the request.

EDIT:

There’s actually a pretty good wiki article here which does a very similar thing.

thank you very much for your reply keith.

i’m getting this error as you suggested…but i’m getting this error…


Trying to get property of non-object 

with following code


<?php Yii::app()->user->model->benefitUses;?>

but my User model is extending CActiveRecord like this…

*/

class User extends CActiveRecord

{

}

Can you post the full stack trace and error message?

Most probably the model returned is null.

I’d guess you are probably not logged in or you have not properly set up the id of WebUser.


$user = Yii::app()->user->model;

if($user == null) throw new CException('User not defined');


// use

CVarDumper::dump($user->benefitUses, 10, true);

It is important to note that Yii::app()->user is a WebUser that is not User (your model class)

this is what i’m getting


PHP notice


Trying to get property of non-object


/Applications/MAMP/htdocs/webapp/protected/models/User.php(99)


087         // class name for the relations automatically generated below.

088         return array(

089             'benefitUses' => array(self::HAS_MANY, 'BenefitUse', 'user_id'),

090              'organisations' => array(self::MANY_MANY, 'Organisation', 'user_organisation(user_id, organisation_id)'),                               

091         );

097     }

098     public function searchNames(){

099         var_dump(Yii::app()->user->model->benefitUses);die;

100         var_dump(Yii::app()->user->benefit);echo "ding";die;

101         return $this->benefit;

102     }

103     /**

104      * @return array customized attribute labels (name=>label)

105      */

106     public function attributeLabels()

107     {

108         return array(

109             'id' => 'ID',

110           

Stack Trace

#0	

–  /Applications/MAMP/htdocs/webapp/protected/controllers/UserController.php(200): User->searchNames()

195     /**

196      * Lists all models.

197      */

198     public function actionIndex()

199     {

200         $models = User::model()->searchNames();var_dump($models);die;

201         $dataProvider=new CActiveDataProvider('User');

202         $this->render('index',array(

203             'dataProvider'=>$dataProvider,

204         ));

205     }

#1	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/actions/CInlineAction.php(50): UserController->actionIndex()

#2	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(309): CInlineAction->runWithParams(array("r" => "user"))

#3	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilterChain.php(134): CController->runAction(CInlineAction)

#4	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilter.php(41): CFilterChain->run()

#5	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(1146): CFilter->filter(CFilterChain)

#6	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CInlineFilter.php(59): CController->filterAccessControl(CFilterChain)

#7	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/filters/CFilterChain.php(131): CInlineFilter->filter(CFilterChain)

#8	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(292): CFilterChain->run()

#9	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CController.php(266): CController->runActionWithFilters(CInlineAction, array("accessControl"))

#10	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CWebApplication.php(283): CController->run("")

#11	

+  /Applications/MAMP/htdocs/framework-1.1.12/web/CWebApplication.php(142): CWebApplication->runController("user")

#12	

+  /Applications/MAMP/htdocs/framework-1.1.12/base/CApplication.php(162): CWebApplication->processRequest()

#13	

–  /Applications/MAMP/htdocs/webapp/index.php(19): CApplication->run()

14 

15 // remove the following line when in production mode

16 defined('YII_DEBUG') or define('YII_DEBUG',true);

17 

18 require_once($yii);

19 Yii::createWebApplication($config)->run();

20 

21 

22 

2013-01-31 17:19:19 Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.4.4 Yii Framework/1.1.12



I’m logged in, I’ve set it u the user id and i’m getting my user id with


	echo Yii::app()->user->id;


CVarDumper::dump(Yii::app()->user->benefitUses, 10, true);

this line is saying


Property "WebUser.benefitUses" is not defined.


CVarDumper::dump(Yii::app()->user, 10, true);

this line is showing


WebUser#1

(

    [model] => null

    [WebUser:_model] => null

    [allowAutoLogin] => true

    [guestName] => 'Guest'

    [loginUrl] => array

    (

        0 => '/site/login'

    )

    [identityCookie] => null

    [authTimeout] => null

    [autoRenewCookie] => false

    [autoUpdateFlash] => true

    [loginRequiredAjaxResponse] => null

    [CWebUser:_keyPrefix] => '00993cbdf63e0aad232dsee020c25071'

    [CWebUser:_access] => array()

    [behaviors] => array()

    [CApplicationComponent:_initialized] => true

    [CComponent:_e] => null

    [CComponent:_m] => null

)

The var dumper should be accessing Yii::app()->user->model->benefitUses;

what about:


CVarDumper::dump(Yii::app()->user->model, 10, true);

null

getting error with

CVarDumper::dump(Yii::app()->user->model->benefitUses);

Trying to get property of non-object

Dear Friend

I hope following will solve the issue.

Add a line in your LoginForm::login




public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

                            $this->_identity->setState('model',User::model()->findByAttributes(array('id'=>$this->_identity->id)));//this is the added line.

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}



It assumes that you have set primarykey of user as property id of UserIdendity in components folder.

Regards.

thanks for your reply seenivasan… i tried it but there is no change in the problem…

Dear Friend

That is finely working in my local host.

Try to use CWebUser rather than your derived class WebUser.

LoginForm::login




public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

                            $this->_identity->setState('model',User::model()->findByPk($this->_identity->id));//this is the added line.

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}




UserIdendity.php




public function getId()

	{

		$user=User::model()->findByAttributes(array('username'=>$this->username,'password'=>$this->password));

		return $user->id;

	}



In a view




if(!Yii::app()->user->getIsGuest())

	echo Yii::app()->user->model->username;




Cheers.

Your WebUser class does not have the ‘benefitUses’ property/method, your User model does. You need to provide that method in WebUser similar to:




public function getBenefitUses() {

    $user = User::model()->with('benefitUses')->findByPk($this->id);

    if ($user) {

        return $user->benefitUses;

    } 


    return array();


}



Then you can use Yii::app()->user->benefitUses to get your array.

Does your getId() method in WebUser return the primary key of the user table? If that is not the case then that is the reason your User model would return a null. I added the ‘with’ since you expect to grab that relation anyways, you may as well have the model do a proper join for a single DB call instead of several.

I hope this helps!

great thanks FrankW. Its now working with your idea :)

Thanks a ton :)

You are very welcome! I am watching this thread, so if you come across a related issue, maybe I can help. I’m far from a Yii master, but the community here is great.