How to set Yii::app()->user->id to be user_id but not username?

After I’ve changed the user table and made a new model,Yii::app()->user->id which is expected to be user_id became username instead.

How to set Yii::app()->user->id to be user_id?

(This is the 4th time i try to post it. Every time i submit this post Chrome would say OOPS, don’t know what’s wrong with this site or it’s just the crazy China great firewall which is now making the Internet a intranet causing trouble)

I found this in Components/useidentity.php


public function authenticate()

	{

		$c=new CDbCriteria;

		$c->condition="username=:username";

		$c->params=array("username"=>$this->username);

		$user = User::model()->find($c);

		if($user === NULL)

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		else if(!$user->validatePassword($this->password, $this->username))

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else{

			$this->_id=$user->id;      //Is this line supposed to indicate that Yii::app()->user->id should be id?

			$this->username = $user->username;

			$this->errorCode=self::ERROR_NONE;

		}

		return $this->errorCode==self::ERROR_NONE;

	}

But Yii::app()->user->id is still a username not a id.

You can find your solution in this guide: Yii Authentication and Authorization :)

You should add a method getId(){return $this->_id}

And in the authenticate add $this->_id = $user->id;

<?php

/**

  • UserIdentity represents the data needed to identity a user.

  • It contains the authentication method that checks if the provided

  • data can identity the user.

*/

class UserIdentity extends CUserIdentity

{

private $_id;

/**


 * Authenticates a user.


 * The example implementation makes sure if the username and password


 * are both 'demo'.


 * In practical applications, this should be changed to authenticate


 * against some persistent user identity storage (e.g. database).


 * @return boolean whether authentication succeeds.


 */

public function authenticate() {

&#036;record = User::model()-&gt;findByAttributes(array('username' =&gt; &#036;this-&gt;username));


if (&#036;record === null)


  &#036;this-&gt;errorCode = self::ERROR_USERNAME_INVALID;


else if (&#036;record-&gt;password &#33;== md5(&#036;this-&gt;password))


  &#036;this-&gt;errorCode = self::ERROR_PASSWORD_INVALID;


else {


    &#036;this-&gt;_id = &#036;record-&gt;id;


  //&#036;this-&gt;setState('email_id', &#036;record-&gt;email_id);


  &#036;this-&gt;errorCode = self::ERROR_NONE;


}


return &#33;&#036;this-&gt;errorCode;

}

public function getId()

{


    return &#036;this-&gt;_id;


}

}

This is my UserIdentity File. Change your File .Clear Cache and Cookies !

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

Now this will give u User Id.

It will Surely Work … Cheers :D