mysql - 我如何在 laravel 中使用 1 个查询来获取 3 个不同的模式表
问题描述
我想采用 3 个不同的模式表,每个模式都需要与一个 params 表连接,所以在这里我尝试采用一个并合并,但我认为该方法无效并且会加载旧数据,这是我的代码
$tabel1 = DB::table('schema1.vendors AS ven')
->orderBy('created_at','desc')
->leftJoin('schema1.admin_params AS ap','ap.admin_param_uuid','=','ven.product_type')
->select('ven.*','ap.description','ap.param_value')
->where('ven.deleted_by',null)
->where('ap.deleted_by',null)
->get();
$tabel2 = DB::table('schema2.vendors AS ven')
->orderBy('created_at','desc')
->leftJoin('schema2.admin_params AS ap','ap.admin_param_uuid','=','ven.product_type')
->select('ven.*','ap.description','ap.param_value')
->where('ven.deleted_by',null)
->where('ap.deleted_by',null)
->get();
$merged = $tabel1->merge($tabel2)->sortByDesc('created_at');
加载的时候感觉我的代码太重了,有什么建议可以简化我的代码吗?因为会有 5 种不同的模式,但被调用的表仍然是供应商
解决方案
可以用unionAll
collection代替merge
,这样可以降低数据库的IO开销。
$tabel1 = DB::table('schema1.vendors AS ven')
->leftJoin('schema1.admin_params AS ap','ap.admin_param_uuid','=','ven.product_type')
->select('ven.column1', 'ven.column2', 'ven....', 'ap.description','ap.param_value')
->whereNull('ven.deleted_by')
->whereNull('ap.deleted_by');
$tabel2 = DB::table('schema2.vendors AS ven')
->leftJoin('schema2.admin_params AS ap','ap.admin_param_uuid','=','ven.product_type')
->select('ven.column1', 'ven.column2', 'ven....','ap.description','ap.param_value')
->whereNull('ven.deleted_by')
->whereNull('ap.deleted_by');
$table1->unionAll($table2)->orderBy('created_at')->get();
PS:您选择的列需要按相同的顺序排列。
推荐阅读
- node.js - 带有上传文件 URL 的 node.js 强大的 make 变量
- ios - SQLite fmdb:如果我不能删除列,删除列数据可以吗?
- laravel - 如何在 laravel 上以一种形式使用两个控制器方法?
- dart - 我如何集成 Android 警报管理器?
- vb.net - 在哪里查看 DataGridView 单元格格式
- matplotlib - matplotlib 错误“362976x273 像素的图像尺寸太大”
- django - 用python打开没有文本的pdf
- mysql - 无法从 Workbench 访问 CentOS 上的 MySQL 服务器
- c# - c# 在表单之间导航
- hibernate - 非法尝试将集合与两个打开的会话相关联-Dropwizard 与 Hibernate