laravel分库分表同一模型能否实现联查?
1. 运行环境
1). 当前使用的 Laravel 版本?
5.7.29
2). 当前使用的 php/php-fpm 版本?
PHP 版本:7.3.4
2. 问题描述?
目前model是动态链接指定分库查询的,现在想请教一下各位大牛,能否在模型中设置所有分库做联查并分页显示
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserCoinWalletFlowExt extends Model
{
protected $connection = 'mysqlRecord'; //库名
public function __construct($user_id = 0)
{
//根据用户id 分配
parent::__construct();
$this->table ='user_coin_wallet_flow'; //连接表
$this->connection =$this->connection.$user_id % 10; //连接库
}
}
尝试过使用这样组合sql语句的方法,但是因为模型是动态链接分库的,获取到的值并不符合预期结果
// 查询集合
$queries = collect();
for ($i = 0; $i < 10; $i++) {
$connection = 'mysqlRecord'.$i;
$table = 'user_coin_wallet_flow';
$queries->push(
DB::connection($connection)->table($table)
->select('id', 'flow_id', 'user_id', 'currency_id','in_out','biz_type','biz_sub_type','biz_detail','remark','create_date')
->where(['biz_type' => 1, 'biz_sub_type' => 1009]));
}
// 出列一张表作为union的开始
$unionQuery = $queries->shift();
// 循环剩下的表添加union
$queries->each(function ($item) use ($unionQuery) {
$unionQuery->unionAll($item);
});
$lists = with(new UserCoinWalletFlowExt(0))->setTable('test')
->from(DB::raw("({$unionQuery->toSql()}) as test"))
->mergeBindings($unionQuery)
->orderBy('create_date', 'desc')
->get();
目前改掉了循环查询的代码了,还是乖乖用原生sql查询,循环拼凑sql语句用union拼接起来,然后直接排序和分页,个人感觉一条查询总比10条查询好些吧。一开始使用laravel的union连接sql语句无效是因为打印出来看到分段指定的sql语句并没有连接到指定的分库,所以怎么union都只在一个库查。几位大佬说的架构建议确实更佳,无奈项目就这样了