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

如何在Laravel Query Builder中实现带unnest()的PostgreSQL查询

用Laravel Query Builder实现PostgreSQL的unnest()关联查询

你的目标是实现这条PostgreSQL原生查询,它通过unnest()把数组字段iteration_times拆成虚拟表,再和主表做交叉连接:

SELECT m.channel, m.qwertz as test, iteration.timestamp as iteration 
FROM m_testate as m, unnest(m.iteration_times) WITH ORDINALITY iteration(timestamp, id) 
WHERE m.project_id = 1 LIMIT 10

你之前用fromSub的写法逻辑不对,因为原生SQL是主表和unnest生成的虚拟表做交叉连接,不是从子查询中获取数据再关联。下面是两种正确的实现方式:

方式一:使用Eloquent模型 + fromRaw

如果Measurement模型对应m_testate表,可以直接用fromRaw还原原生SQL的表结构:

$result = Measurement::select(
        'channel',
        'qwertz as test',
        DB::raw('iteration.timestamp as iteration')
    )
    ->fromRaw('m_testate as m, unnest(m.iteration_times) WITH ORDINALITY iteration(timestamp, id)')
    ->where('project_id', $project_id)
    ->limit(10)
    ->get();

方式二:使用Query Builder + crossJoinRaw

用crossJoinRaw明确声明交叉连接,语义更清晰:

$result = DB::table('m_testate as m')
    ->select(
        'm.channel',
        'm.qwertz as test',
        'iteration.timestamp as iteration'
    )
    ->crossJoinRaw('unnest(m.iteration_times) WITH ORDINALITY iteration(timestamp, id)')
    ->where('m.project_id', $project_id)
    ->limit(10)
    ->get();

这两种写法都会生成和你原生SQL完全一致的查询语句,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:20:18