【问题标题】:Get User Profile - dektrium/yii2-user Yii2获取用户资料 - dektrium/yii2-user Yii2
【发布时间】:2016-02-10 07:24:14
【问题描述】:

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

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

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

我用谷歌搜索了这个问题,但什么也没找到...帮帮我吧伙计们..

【问题讨论】:

    标签: php yii2 yii2-user


    【解决方案1】:

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

    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;
    

    将返回与User 关联的Profile 模型数据

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

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

    详情请见dektrium\user\models\Profile。


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

    【讨论】:

    • 嘿嘿嘿!我无法弄清楚使用Yii::$app->user->identity->profile; 会输出什么数据。但是我发现我的代码的问题是:我正在尝试访问 dektrium 的 User.php 中存在的方法,默认情况下,代码 Yii::$app->user->getProfile; 正在搜索 yii\web\User中的方法> 不在 dektrium/../User 中
    • 更新帖子以解释如何获取配置文件数据
    【解决方案2】:

    如果你有一个用户实例($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();
    

    【讨论】:

    • 不,Yii::$app->user不是用户模型的接口,但是可以通过identity获取当前登录的用户
    • 公共函数 getId() { $identity = $this->getIdentity();返回 $identity !== null ? $identity->getId() : null; }
    • @stig-js 您描述的方法效率不高。目前我使用的是$profile = Profile::findOne(Yii::$app->user->getID()); 而不是这个,我认为它比你给出的更好......
    • @choxx findOne 在内部使用 findbycondition 也调用 find 方法:yiiframework.com/doc-2.0/…github.com/yiisoft/yii2/blob/master/framework/db/…
    • @jacmoe 你说得对,正如我发布的链接中所说,Yii::$app->user 是管理用户身份验证状态的“用户”应用程序组件的类.因此,在配置中,您已将用户类定义为 dektrium one,但我已经简化了太多。
    【解决方案3】:

    试试这个

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

    【讨论】:

    • 最好解释一下为什么这样可以让他理解为什么他的公式不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多