thinkphp的多库查询有很多种,今天到需求是在每个工程中都有对某个数据库的操作,这个连接就一个model类使用。
反正就是解决多库查询,库可以不再一个服务器上。
连接写在model中
配置文件中:
/* 全局数据库设置 */ 'DB_TYPE' => 'mysql', // 数据库类型 'DB_HOST' => 'localhost', // 服务器地址 'DB_NAME' => 'php34', // 数据库名 'DB_USER' => 'root', // 用户名 'DB_PWD' => 'root', // 密码 'DB_PORT' => '3306', // 端口 'DB_PREFIX' => 'wx_', // 数据库表前缀 'DB_CHARSET' => 'utf8', // 数据库编码 'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志 //定义特定的数据连接 'SUPERVISE_DB' => array( 'DB_TYPE' => 'mysql', 'DB_USER' => 'root', 'DB_PWD' => 'root', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '3306', 'db_name' => 'spring4', 'db_charset' => 'utf8', 'DB_PREFIX' => 'sv_', // 数据库表前缀 ), 在要用到特定数据库连接的model中 自己定义的model名字的后缀是 .class.php 给数据库连接属性赋值要放在父类构造方法的前面 <?php /** * Created by PhpStorm. * User: qxb-810 * Date: 2017/5/4 * Time: 19:49 */ namespace Home\Model; use Think\Model; class VisitModel extends Model { // 采用数组方式定义 protected $connection; protected $tablePrefix; public function __construct() { //初始化数据库连接 $this->connection = C('SUPERVISE_DB'); $this->tablePrefix = C('SUPERVISE_DB')['DB_PREFIX']; parent::__construct(); } public function test() { return 'VisitModel function...'; } } 还有个用全局连接参数的自定义model类<?php namespace Home\Model; use Think\Model; /** * Created by PhpStorm. * User: qxb-810 * Date: 2017/5/4 * Time: 17:36 */ class UserModel extends Model { // 表名 protected $tableName = 'user'; public function __construct() { parent::__construct(); } public function getUserById($id) { return 'aaa'; } } 接下来就是测试类 <?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { private $visit; private $user; public function __construct() { parent::__construct(); $this->user = D('User'); $this->visit = D('Visit'); } public function test() { dump('IndexController test method'); dump($this->user); dump($this->visit); dump($this->user); dump($this->visit); } } 一切ok