如何在Elixir Ecto中使用'between'创建SQL

13

我想在Elixir Ecto中使用关键字'between'创建SQL。

我知道如何使用like创建SQL:

where: like(t.descript, ^some_description)

但当我尝试像like一样使用它时:

where: between(t.start_date, ^start_date, ^end_date)

我收到了“无效”的错误消息。

** (Ecto.Query.CompileError) `between(t.start_date(), ^start_date, ^end_date)` is not a valid query expression.**

我该如何以正确的方式去做?

提前感谢!!

3个回答

23

我认为Ecto没有提供between子句。你可以通过使用其他方式来完成你的任务。

where: t.start_date >= ^start_date,
where: t.start_date <= ^end_date

你的意思是 start_date <= ^end_date 吗? - Ramon Snir
9
为了方便他人,您可以将这些内容合并成一行,并使用“and”连接。其中:t.start_date >= ^start_date and t.start_date <= ^end_date。 - Dustin

14

2
您可以使用@Horvo提供的代码片段自己制作between宏:
@doc """
Checks if the first value is between the second and third value.
"""
defmacro between(value, left, right) do
  quote do
    fragment("? BETWEEN ? AND ?", unquote(value), unquote(left), unquote(right))
  end
end

并且您可以像希望的那样使用它:

where: between(t.start_date, ^start_date, ^end_date)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接