thinkphp5 如何连接第二个数据库 或在多个数据?

  1. 复制 /application/database.php -> database2.php, 配置第二个数据库信息到 database2.php

  2. 在 /application/config.php 导入 $db_config_cards = require_once('database2.php');

  3. 在 /application/config.php 参数加一项 -> 'db_config_cards' => $db_config_cards;(如果有第三个数据,继续在下面添加配置 'db_config_cards3' => $db_config_cards3)

  4. WX20200206-232415@2x

  5.  用第二个数据库连接创建一个model试试,假设第二个数据库表里有个tp5_news_content表

  6. 创建模型文件/application/index/model/NewsContent.php 代码如下


  7. <?php
    namespace app\Index\model;
    use think\model;
    class NewsContent extends Model
    {
        // 指定连接第二个数据库
        protected $connection = 'db_config_cards';
        // 这个配置是解决 toArray() 方法报错的 
        protected $resultSetType = 'collection';
    }
  8. 在控制器里 使用NewsContent    

  9. public function test()
    {
        $news = new \app\Index\model\NewsContent();
        $list = $news->select()->toArray();
        print_r($list);
    }