Get User Profile - dektrium/yii2-user Yii2

前提是你 提交于 2019-12-12 15:10:11

问题


I have used dektrium/yii2-user in my application. And there is a method named getID() in User.php of vendor/dektrium and this method can be accessed by Yii::$app->user->getID() and returns id of the logged in user.

However, there is another method named getProfile() whose function is to return complete profile details of currently logged in user. But, this method is giving 500-internal server error.

exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\web\User::getProfile()' in ... ...

I Googled the issue but found nothing... Help me folks..


回答1:


I believe that you can get the profile of the currently logged in user like this:

Yii::$app->user->identity->profile;

because Yii::$app->user->identity returns the current user - the User object.

You are confusing Yii's web user object with the user model :)

EDIT:

Yii::$app->user is referring to yii\web\User - the application component that manages the user authentication status.

You ask that User component to get the 'identity' which is :

IdentityInterface is the interface that should be implemented by a class providing identity information

In this case, Dektrium User model implements the IdentityInterface and you are able to call getId on it and get the id for the User model.

class User extends ActiveRecord implements IdentityInterface

This code:

Yii::$app->user->identity->profile;

Will return the Profile model data associated with the User

And you can access it's fields directly:

Yii::$app->user->identity->profile->location;

See dektrium\user\models\Profile for details.


People always gets confused about yii\web\User, the IdentityInterface and the User model.. Myself included :p




回答2:


If you have an instance of an user ($user), you can use the getProfile() function:

$profile = $user->getProfile()->one();

And it returns profile record from that user.

If you don't have an instance of user, but the id ($user_id), you could get an instance of Profile model directly:

$profile = Profile::find()->where(['user_id' => $user_id)->one();

And Yii::$app->user is an interface to the user model defined in your app (dektrium user model in this case): http://www.yiiframework.com/doc-2.0/yii-web-user.html

to sum up:

$user_id = Yii::$app->user->getID();
$profile = Profile::find()->where(['user_id' => $user_id)->one();



回答3:


Try this one

\app\models\User::findOne(Yii::$app->user->identity->id)->profile;


来源:https://stackoverflow.com/questions/35309138/get-user-profile-dektrium-yii2-user-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!