簡體   English   中英

獲取用戶信息 - dektrium / yii2-user Yii2

[英]Get User Profile - dektrium/yii2-user Yii2

我在我的應用程序中使用了dektrium / yii2-user 並且在vendor / dektrium的 User.php中有一個名為getID()的方法,該方法可以通過Yii::$app->user->getID()並返回登錄用戶的id

但是,還有另一種名為getProfile()的方法,其功能是返回當前登錄用戶的完整配置文件詳細信息。 但是,這種方法給出了500內部服務器錯誤。

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

我用谷歌搜索了這個問題但沒有發現任何事情......幫助我的人們......

我相信您可以獲得當前登錄用戶的個人資料,如下所示:

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

因為Yii::$app->user->identity返回當前用戶 - User對象。

您將Yii的Web用戶對象與用戶模型混淆:)

編輯:

Yii::$app->user指的是yii\\web\\User - 管理用戶身份驗證狀態的應用程序組件。

您要求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

如果您有一個用戶實例( $ user ),則可以使用getProfile ()函數:

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

它返回該用戶的個人資料記錄。

如果您沒有user的實例,而是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();

試試這個吧

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM