3

我在我的应用程序中使用了 dektrium/yii2-user在vendor/dektriumgetID()User.php中有一个名为的方法,该方法可以被登录用户访问并返回。Yii::$app->user->getID()id

但是,还有另一种名为的方法getProfile(),其功能是返回当前登录用户的完整配置文件详细信息。但是,这种方法会给出 500-internal server error。

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

我用谷歌搜索了这个问题,但一无所获......帮帮我吧伙计们..

4

3 回答 3

5

我相信您可以像这样获取当前登录用户的个人资料:

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

因为Yii::$app->user->identity返回当前用户 -User对象。

您将 Yii 的网络用户对象与用户模型混淆了:)

编辑:

Yii::$app->user指的是yii\web\User——管理用户认证状态的应用程序组件。

您要求该用户组件获取“身份”,即:

IdentityInterface 是应该由提供身份信息的类实现的接口

在这种情况下,Dektrium User 模型实现了IdentityInterface并且您可以调用getId它并获取 User 模型的 id。

class User extends ActiveRecord implements IdentityInterface

这段代码:

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

将返回ProfileUser

您可以直接访问它的字段:

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

详情请参阅dektrium\user\models\Profile


人们总是对 yii\web\User、IdentityInterface 和 User 模型感到困惑。包括我自己:p

于 2016-02-11T18:40:14.070 回答
1

如果你有一个用户实例($user),你可以使用getProfile () 函数:

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

它从该用户返回配置文件记录。

如果您没有用户实例,但有 id ( $user_id ),则可以直接获取 Profile 模型的实例:

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

并且Yii::$app->user是您的应用程序中定义的用户模型的接口(在本例中为 dektrium 用户模型):http ://www.yiiframework.com/doc-2.0/yii-web-user.html

总结一下:

$user_id = Yii::$app->user->getID();
$profile = Profile::find()->where(['user_id' => $user_id)->one();
于 2016-02-12T00:25:06.677 回答
0

试试这个

\app\models\User::findOne(Yii::$app->user->identity->id)->profile;
于 2016-02-11T19:59:06.363 回答