我正在构建一个简单的搜索功能,我希望找到字符串字段中有一个字符串的所有记录。
这是我尝试过的。
term = "Moby"
MyApp.Book
|> where([p], String.contains?(p, term))
|> order_by(desc: :inserted_at)这将返回下列书籍:
但我明白:
`String.contains?(p, term)` is not a valid query expression发布于 2016-08-07 04:47:21
您必须使用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 $1) ORDER BY p0.\"inserted_at\" DESC",
["%Foo\\%Bar%"]}如果不进行替换,像"a%b"这样的术语将与"azb"匹配,因为%需要转义,或者它匹配任何零个或多个字符的序列。
发布于 2016-08-06 05:19:56
你是怎么做到的:
results =
from b in Book,
where: ilike(t.name, ^"%#{params["term"]}%"),
order_by: [desc: :inserted_at]https://stackoverflow.com/questions/38798747
复制相似问题