I have two databases, and every database has the same table with the same fields, but how do I get all records from all of two databases at the same time in Yii 2.0?
Multiple database connections and Yii 2.0
yii2
Related Solutions
You can implement database user management using extesions like https://github.com/amnah/yii2-user.
OR
If you want to write your own custom script to manage the users you can override Yii2 identityClass.
In the component section of your config add:
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
Please note that your user model MUST IMPLEMENT \yii\web\IdentityInterface
Here is the example of the model class that you can use to implement database authentication
namespace app\models;
//app\models\gii\Users is the model generated using Gii from users table
use app\models\gii\Users as DbUser;
class User extends \yii\base\Object implements \yii\web\IdentityInterface {
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $email;
public $phone_number;
public $user_type;
/**
* @inheritdoc
*/
public static function findIdentity($id) {
$dbUser = DbUser::find()
->where([
"id" => $id
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$dbUser = DbUser::find()
->where(["accessToken" => $token])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username) {
$dbUser = DbUser::find()
->where([
"username" => $username
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* @inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return $this->password === $password;
}
}
I hope that would be helpful to you . Cheers :)
If you use ActiveForm widget use this:
<?php
$items = ArrayHelper::map(Model::find()->all(), 'id', 'name');
$form->field($model, 'attribute')->dropDownList($items)
?>
Best Solution
First you need to configure your databases like below:
Then you can simply:
If you are using an active record model, in your model you can define:
Then:
If you have set
db1
in thegetDb()
method, the result will be fetched fromdb1
and so on.