天天看點

TP5 連接配接多個資料庫及使用方法

工作中,有是需要連接配接多個資料庫,thinkphp5中也可以連接配接多個資料庫,不影響主資料庫,

在application/config.php中加入配置,主資料庫配置檔案 database.php不需要動

//資料庫配置2
'db_config2' => [
 // 資料庫類型
    'type'        => 'mysql',
    // 資料庫連接配接DSN配置
    'dsn'         => '',
    // 伺服器位址
    'hostname'    => '127.0.0.1',
    // 資料庫名
    'database'    => 'tp5_Db2',
    // 資料庫使用者名
    'username'    => 'root',
    // 資料庫密碼
    'password'    => 'root',
    // 資料庫連接配接端口
    'hostport'    => '',
    // 資料庫連接配接參數
    'params'      => [],
    // 資料庫編碼預設采用utf8
    'charset'     => 'utf8',
    // 資料庫表字首
    'prefix'      => 'hf_',
],
           

調用方法:

$res=Db::connect(config('db_config2'))->name('tp_shop')->order('id desc')->paginate(22);
$this->assign('res',$res);