我必须在我的Database.php中建立数据库组
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'primaryDB',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
public $second = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'secondaryDB',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];我有两种类型的登录角色(分发服务器和供应商)。在分发服务器登录中,我想使用primaryDB和secondaryDB的供应商登录。
发行商用户名- demo@distributor.com
供应商用户名- demo@vendor.com
AuthController
public function auth() {
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$database = explode('@',$username);
$database = explode('.',$database[1])[0];
if($database == 'distributor') {
$userInfo = $this->AuthModel->getDistributor($username);
} else {
$this->db = db_connect('second');
$userInfo = $this->AuthModel->getVendor($username);
}
print_r($userInfo);
}AuthModel
public function getDistributor($username)
{
$builder = $this->db->table('distributors');
return $builder->get()->getRowArray();
}
public function getVendor($username)
{
$builder = $this->db->table('vendors');
return $builder->get()->getRowArray();
}当我用我的供应商帐户登录时,第二个数据库没有加载。它返回其他条件下的默认数据库值。有人能告诉我加载多个数据库的正确方法吗?因为我可以有两个以上的数据库进行登录。
发布于 2022-05-27 09:00:24
在您的AuthModel中,使用db_connect('...')代替$this->db->。即:
AuthModel.php
public function getDistributor($username)
{
$builder = db_connect('default')->table('distributors');
return $builder->get()->getRowArray();
}
public function getVendor($username)
{
$builder = db_connect('second')->table('vendors');
return $builder->get()->getRowArray();
}附录
解决方案2:或者,您可以动态地在模型实例上设置DBGroup。即:
AuthModel.php
// ...
public function setDB(string $databaseGroup): self {
$this->db = db_connect($databaseGroup);
return $this;
}
public function getDistributor($username)
{
$builder = $this->db->table('distributors');
return $builder->get()->getRowArray();
}
public function getVendor($username)
{
$builder = $this->db->table('vendors');
return $builder->get()->getRowArray();
}
// ...AuthController.php
public function auth() {
// ...
$userInfo = ($database === 'distributor') ?
$this->AuthModel->getDistributor($username)
: $this->AuthModel->setDB("second")->getVendor($username);
$this->AuthModel->setDB("default"); // Reset DBGroup.
print_r($userInfo);
}https://stackoverflow.com/questions/72401927
复制相似问题