
Foreword:
Sometimes a management background needs to involve multiple databases. For example, mall management, live broadcast management, message management, etc., they all have their own databases. At this time, you need to connect to multiple databases and process them. thinkphp can support multiple database connections.
How to deal with it?
1. Configure multiple databases
The database information in database.php will be connected by default.
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '', // 数据库名 'database' => '', // 数据库用户名 'username' => '', // 数据库密码 'password' => '', // 数据库连接端口 'hostport' => '3306', // 数据库编码默认采用utf8 'charset' => '', // 数据库表前缀 'prefix' => '' ];
tp5 will automatically load database.php
(Recommended tutorial: thinkphp tutorial)
We can create a few more in the extra folder Configuration of other databases, such as database_mall, database_live, database_app, etc.
2. Initialization
Initialize in the model module
<?php
namespace app\admin\model;
use think\Model;
use think\Db;
class LiveRecharge extends Model
{
protected $db_app;
function __construct()
{
$this->db_app = Db::connect('database_app');
}
}3. Use
$this->db_app->table('order')->select();
so that you can query data in other databases.
The following is the complete code:
<?php
namespace app\admin\model;
use think\Model;
use think\Db;
class LiveRecharge extends Model
{
protected $db_app;
function __construct()
{
$this->db_app = Db::connect('database_app');
}
// 获取分页
public function getList($customer_id = '',$nickname = '',$paytime = '',$pagesize = '')
{
$pagesize = $pagesize && $pagesize > 0 ? $pagesize : config('default_page_size');
$where = array();
$where['o.type'] = 3;
if ($customer_id) {
$where['o.uid'] = $customer_id;
}
if ($nickname) {
$where['c.NickName'] = ['like','%'.$nickname.'%'];
}
if ($paytime) {
$where['o.addtime'] = array(['>',$paytime.' 00:00'], ['<',$paytime.' 23:59']);
}
$result = $this->db_app->table('order')
->alias('o')
->where($where)
->join('customer c','o.uid = c.Id')
->field('o.*,c.NickName as nickname')->paginate($pagesize,false,[
'query' => [
'customer_id'=>$customer_id,
'nickname'=>$nickname,
'paytime'=>$paytime
]
]);
$page = $result->render(); // 分页
$data = $result->all(); // 数据
foreach ($data as $k=>$v) {
$data[$k]['diamond'] = intval($v['money'])*10;
}
// dump($this->db_app->getLastSql());
$total_diamond = $this->db_app->table('order')->where('type',3)->sum('money*10');
$outData['page'] = $page;
$outData['data'] = $data;
$outData['total_diamond'] = $total_diamond;
return $outData;
}
}For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!
The above is the detailed content of How to use the tp5 framework to implement multi-database queries. For more information, please follow other related articles on the PHP Chinese website!
What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PMThe article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.
How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PMArticle discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.
What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PMThe article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges
How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PMThe article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]
What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PMThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159
How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PMThe article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.
What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PMThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.
How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PMThe article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.






