在ThinkPHP中,可以通过配置文件实现多个数据库连接。具体步骤如下:
database.php
配置文件,一般位于application\config
目录下。return [
// 默认数据连接配置
'default' => [
'type' => 'mysql',
'hostname' => 'localhost',
'database' => 'test',
'username' => 'root',
'password' => 'root',
],
// 另一个数据库连接配置
'db2' => [
'type' => 'mysql',
'hostname' => 'localhost',
'database' => 'test2',
'username' => 'root',
'password' => 'root',
],
];
namespace app\index\model;
use think\Model;
class UserModel extends Model
{
// 使用默认数据库连接配置
protected $connection = 'default';
// 使用另一个数据库连接配置
protected $connection = 'db2';
}
需要注意的是,在使用不同数据库连接时,应该避免使用跨库查询等操作,以免出现数据不一致的情况。