首页 > 解决方案 > 我如何在 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 种不同的模式,但被调用的表仍然是供应商

标签: mysqllaravellaravel-5eloquent

解决方案


可以用unionAllcollection代替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:您选择的列需要按相同的顺序排列。


推荐阅读