You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中实现指定UNION ALL查询并按newDate升序排序?

嘿,我来帮你把这段SQL转换成Laravel里的实现方式,给你准备了两种常用方案,看你需求选:

方法一:使用Laravel查询构建器(推荐)

这种方式更贴合Laravel的开发规范,代码可读性和可维护性都更强:

use Illuminate\Support\Facades\DB;

// 构建第一个子查询:取due1符合条件的记录,别名newDate
$query1 = DB::table('equipments')
    ->select('*', DB::raw('due1 as newDate'))
    ->where('due1', '<>', '1990-01-01');

// 构建第二个子查询:取due2符合条件的记录,别名newDate
$query2 = DB::table('equipments')
    ->select('*', DB::raw('due2 as newDate'))
    ->where('due2', '<>', '1990-01-01');

// 构建第三个子查询:取due3符合条件的记录,别名newDate
$query3 = DB::table('equipments')
    ->select('*', DB::raw('due3 as newDate'))
    ->where('due3', '<>', '1990-01-01');

// 合并三个查询,按newDate升序排序后获取结果
$result = $query1->unionAll($query2)
    ->unionAll($query3)
    ->orderBy('newDate', 'asc')
    ->get();

简单说明下:

  • 三个子查询分别对应你原SQL里的三个SELECT语句,用DB::raw()来处理字段别名的逻辑
  • unionAll()方法和你原SQL的UNION ALL作用完全一致,会保留所有符合条件的记录(包括重复的)
  • 最后通过orderBy()指定排序规则,get()方法会返回包含结果集的Collection对象
方法二:直接执行原生SQL

如果你想直接复用原SQL语句,也可以用Laravel的原生查询方法:

use Illuminate\Support\Facades\DB;

// 直接复用你的原SQL语句
$sql = 'SELECT *, due1 as newDate FROM equipments WHERE due1 <> "1990-01-01" 
        UNION ALL 
        SELECT *, due2 as newDate FROM equipments where due2 <> "1990-01-01" 
        UNION ALL 
        SELECT *, due3 as newDate FROM equipments WHERE due3 <> "1990-01-01" 
        ORDER BY newDate ASC';

$result = DB::select($sql);

要是后续需要动态替换日期参数,建议用参数绑定来避免SQL注入问题,示例如下:

use Illuminate\Support\Facades\DB;

$excludeDate = '1990-01-01';
$sql = 'SELECT *, due1 as newDate FROM equipments WHERE due1 <> ? 
        UNION ALL 
        SELECT *, due2 as newDate FROM equipments where due2 <> ? 
        UNION ALL 
        SELECT *, due3 as newDate FROM equipments WHERE due3 <> ? 
        ORDER BY newDate ASC';

// 把参数放进数组里,Laravel会自动处理绑定
$result = DB::select($sql, [$excludeDate, $excludeDate, $excludeDate]);

内容的提问来源于stack exchange,提问作者marco_nz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:34:12