我如何强制yii2模块为所有他的模型使用特定的连接? [英] How i can force an yii2 module to use a specific connection for all his models?
问题描述
在模块上,我添加了一个名为db的组件,就像主Yii组件一样,用于数据库连接的数据,我需要在模块中每次针对所有模型(而不是主数据库)在其配置中指定的db都使用连接,我该怎么做?
on a module I have add a component named db where i put, like the main Yii component, the data for database connection, I need in my module use everytime the db specified in his configuration for all models and not the main database connection, how I can do this?
推荐答案
您有几种方法,例如在app/config/main.php中使用单独的配置 例如,将特定的dbMyMod添加到组件config
You have several way eg. using a separated configuration in app/config/main.php eg adding a specific dbMyMod to component config
return [
// ...
'components' => [
// ...
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'dbMyMod ' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=hostForMudle;dbname=module_db_name',
'username' => 'user_module_name',
'password' => 'password',
'charset' => 'utf8',
],
],
或一种不需要在应用程序/配置中进行静态配置的方式
or one way that not require a static configuration in app/confing
可以基于返回正确数据库连接的模块函数
could be based on a module function that return a proper db connection
public function myModuleDbCon()
{
$myDbCon = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
return myDbConn;
}
然后在您的模块中,您可以检索模块的数据库连接
then in you module you can retrive the module db connection
aDbConn = Yii::$app->getModule('my_module_name')->myModuleClass->myModuleDbCon();
.
$command = $aDbConn->createCommand('SELECT * FROM myTable');
$result= $command->queryAll();
这篇关于我如何强制yii2模块为所有他的模型使用特定的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!