使用max()实现HaveRaw()时出错

时间:2018-12-06 23:59:26

标签: knex.js objection.js

我正在尝试将此SQL查询转换为knex:

select
    "events".*,
    "events"."id",
    "events"."version",
    "events"."reviewed_at",
    "events"."source_id"
from "events"
inner join "events" as "events2" on "events".source_id = "events2".source_id
inner join "event_dates" on "events"."id" = "event_dates"."event_id"
where "event_dates"."end_date" > 'NOW()' 
group by
    "events"."id",
    "events"."version",
    "events"."reviewed_at",
    "events"."source_id"
having MAX("events2".reviewed_at) = "events".reviewed_at;

但是我似乎无法正确理解havingRaw()部分。这是我截至目前的havingRaw()

.havingRaw('MAX("events2".reviewed_at) = ?', "events".reviewed_at)

如果我排除了havingRaw(..),我的查询就会执行,但是我确实需要添加条件。

1 个答案:

答案 0 :(得分:0)

至少您的代码似乎有语法错误,并且您使用的raw API错误:

.havingRaw('MAX("events2".reviewed_at) = ?', "events".reviewed_at)

您正在尝试读取字符串文字reviewed_at的属性"event" ...试试:

.havingRaw('MAX(??) = ??', ["events2.reviewed_at", "events.reviewed_at"])

??是标识符替换的地方,它会自动正确引用。如果仅使用?替换,则knex会尝试将替换作为值绑定传递给数据库驱动程序。