yii2 使用多个数据库的案例

配置:

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=ip;dbname=dbname',
        'username' => 'username',
        'password' => 'pwd',
        'charset' => 'utf8',
    ],
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=ip;dbname=dbname2',
        'username' => 'username',
        'password' => 'pwd',
        'charset' => 'utf8',
    ],
],

模型:

class Norders extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'norders';
    }

    public static function getDb() {
        //var_dump(Yii::$app->get('db2'));die;
        return Yii::$app->get('db2'); //dbresult 就是你自己的配置的DB 名字
    }
}

控制器:

public function actionAddNorders(){
    $data = Norders::find()->all();
    var_dump($data);die;
}

 

posted @ 2018-12-10 15:22  一个人的孤独自白  阅读(493)  评论(0编辑  收藏  举报