Php 从不同的数据库登录Yi2
我想使用来自不同数据库的两个表来实现yii2basic应用程序中的登录功能 在登录视图中,我添加了一个新字段:Php 从不同的数据库登录Yi2,php,database,authentication,yii2,Php,Database,Authentication,Yii2,我想使用来自不同数据库的两个表来实现yii2basic应用程序中的登录功能 在登录视图中,我添加了一个新字段: <?= $form->field($model, 'username') ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'choice') ?> User.php具有以下功能: public sta
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'choice') ?>
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仍会刷新登录页面。如果使用该场景,请避免在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']);
// ......
如果使用该场景,请避免在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']);
// ......
此链接可能有助于您在Yii2中使用多重身份,此链接可能有助于您在Yii2和此Sage建议中使用多重身份。谢谢,卡克。明智的建议。谢谢,卡克。