字符串字段包含其他字符串的 Ecto 查询
Ecto query where string field contains other string
我正在构建一个简单的搜索功能,我想查找在字符串字段中包含字符串的所有记录。
这是我尝试过的。
term = "Moby"
MyApp.Book
|> where([p], String.contains?(p, term))
|> order_by(desc: :inserted_at)
这将 return 以下书籍:
- 白鲸记
- Sandich Moby Lean
- 我的 Moby 和示例
但我得到:
`String.contains?(p, term)` is not a valid query expression
操作方法如下:
results =
from b in Book,
where: ilike(t.name, ^"%#{params["term"]}%"),
order_by: [desc: :inserted_at]
您必须使用 String.replace/3
转义输入中的 %
(如果它是由最终用户输入的),然后在查询中使用 like
:
|> where([p], like(p.title, ^"%#{String.replace(term, "%", "\%")}%"))
示例:
iex(1)> term = "Foo%Bar"
iex(2)> query = MyApp.Post |> where([p], like(p.title, ^"%#{String.replace(term, "%", "\%")}%")) |> order_by(desc: :inserted_at)
#Ecto.Query<from p in MyApp.Post, where: like(p.title, ^"%Foo\%Bar%"),
order_by: [desc: p.inserted_at]>
iex(3)> Ecto.Adapters.SQL.to_sql(:all, MyApp.Repo, query)
{"SELECT p0.\"id\", p0.\"title\", p0.\"user_id\", p0.\"inserted_at\", p0.\"updated_at\" FROM \"posts\" AS p0 WHERE (p0.\"title\" LIKE ) ORDER BY p0.\"inserted_at\" DESC",
["%Foo\%Bar%"]}
如果您不进行替换,像 "a%b"
这样的术语将匹配 "azb"
,因为 %
需要转义,或者它匹配零个或多个字符的任何序列。
我正在构建一个简单的搜索功能,我想查找在字符串字段中包含字符串的所有记录。
这是我尝试过的。
term = "Moby"
MyApp.Book
|> where([p], String.contains?(p, term))
|> order_by(desc: :inserted_at)
这将 return 以下书籍:
- 白鲸记
- Sandich Moby Lean
- 我的 Moby 和示例
但我得到:
`String.contains?(p, term)` is not a valid query expression
操作方法如下:
results =
from b in Book,
where: ilike(t.name, ^"%#{params["term"]}%"),
order_by: [desc: :inserted_at]
您必须使用 String.replace/3
转义输入中的 %
(如果它是由最终用户输入的),然后在查询中使用 like
:
|> where([p], like(p.title, ^"%#{String.replace(term, "%", "\%")}%"))
示例:
iex(1)> term = "Foo%Bar"
iex(2)> query = MyApp.Post |> where([p], like(p.title, ^"%#{String.replace(term, "%", "\%")}%")) |> order_by(desc: :inserted_at)
#Ecto.Query<from p in MyApp.Post, where: like(p.title, ^"%Foo\%Bar%"),
order_by: [desc: p.inserted_at]>
iex(3)> Ecto.Adapters.SQL.to_sql(:all, MyApp.Repo, query)
{"SELECT p0.\"id\", p0.\"title\", p0.\"user_id\", p0.\"inserted_at\", p0.\"updated_at\" FROM \"posts\" AS p0 WHERE (p0.\"title\" LIKE ) ORDER BY p0.\"inserted_at\" DESC",
["%Foo\%Bar%"]}
如果您不进行替换,像 "a%b"
这样的术语将匹配 "azb"
,因为 %
需要转义,或者它匹配零个或多个字符的任何序列。