亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從不同的數據庫登錄 Yii2

從不同的數據庫登錄 Yii2

PHP
哆啦的時光機 2022-12-11 09:35:45
我想在 Yii2 基本應用程序中使用來自不同數據庫的兩個表作為登錄功能。在登錄視圖中,我添加了一個新字段:<?= $form->field($model, 'username') ?><?= $form->field($model, 'password')->passwordInput() ?><?= $form->field($model, 'choice') ?>在 LoginForm 中,我修改了這個:public function getUser() {    if ($this->_user === false && $this->choice == 1) {                    $this->_user = User::findByUsername($this->username);    }    else if ($this->_user === false && $this->choice == 2) {        $this->_user = UserPerusahaan::findByUsername($this->username);    }    return $this->_user;}User.php 有這個:public static function getDb() {    return \Yii::$app->dblogin;  // use the "db2" application component}public static function tableName() {    return 'pengguna';}UserPerusahaan.php 與 User.php 的不同之處在于:/*public static function getDb() {    return \Yii::$app->dblogin; }*/public static function tableName() {    return 'perusahaan';}當我嘗試登錄時,它只會刷新登錄頁面。我在這里錯過了什么?或者還有其他更好的實用方法嗎?編輯:我嘗試將其添加到 web.php 中的組件:'user' => [        'class' => 'yii\web\User',        'identityClass' => 'app\models\User',        'enableAutoLogin' => true,],'userperusahaan' => [        'class' => 'yii\web\User',        'identityClass' => 'app\models\UserPerusahaan',        'enableAutoLogin' => true, ],這是 LoginForm.php:public function login() {    if ($this->validate()&& $this->choice == 1) {        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);    }    else if ($this->validate()&& $this->choice == 2) {        return Yii::$app->userperusahaan->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);    }    return false;}使用 $choice = 1 的登錄有效,但使用 $choice = 2 仍然讓我刷新登錄頁面。
查看完整描述

1 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

如果您使用該方案,請避免在您的 accessControl 中使用角色“@”。角色“@”只適用于 Yii::$app->user,所以如果你使用不同的組件登錄(例如 Yii::$app->userPerusahaan->login()),它不會算作具有角色的注冊用戶“ @”。像這個例子一樣修改你的 siteController。


public function behaviors()

{

    return [

        'access' => [

            'class' => AccessControl::className(),

            'rules' => [

                [

                    'actions' => ['index', 'login'],

                    'allow' => true,

                    'roles' => ['?'],

                ],

                [

                    'actions' => ['logout'],

                    'allow' => true,

                    'roles' => ['@'],

                ],

            ],

        ],

        'verbs' => [

            'class' => VerbFilter::className(),

            'actions' => [

                'logout' => ['post'],

            ],

        ],

    ];

}


public function actionIndex()

{

    if(Yii::$app->user->isGuest && Yii::$app->userPerusahaan->isGuest) return $this->redirect(['login']);

    //  ......


查看完整回答
反對 回復 2022-12-11
  • 1 回答
  • 0 關注
  • 120 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號