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

Phoenix/Ecto查询对象数组匹配报any(l.signers)非有效表达式如何解决

Ecto数组包含匹配查询解决方案

错误原因

你遇到的Ecto.Query.CompileError是因为Ecto查询语法不支持直接按值 == any(数组字段)的格式编写查询语句,需要用Ecto原生支持的数组包含检查方法,或配合SQL片段实现逻辑。

正确实现方案

方案1:使用Ecto内置contains?函数(推荐)

Ecto 3.0+ 提供了内置的contains?/2查询函数,跨数据库兼容,写法简洁:

from l in Listing,
  where: contains?(l.signers, "xxxxxx@gmail.com")
|> Repo.all()

如果需要匹配数组同时包含多个值,直接传入数组参数即可:

from l in Listing,
  where: contains?(l.signers, ["xxxxxx@gmail.com", "yyyyyy@gmail.com"])
|> Repo.all()

方案2:使用fragment配合PostgreSQL原生ANY操作符

如果你需要直接调用PostgreSQL的ANY语法,可以用fragment包裹原生SQL逻辑:

from l in Listing,
  where: fragment("? = ANY(?)", "xxxxxx@gmail.com", l.signers)
|> Repo.all()

注意事项

请确保Listing表的signers字段在迁移中定义为数组类型,以PostgreSQL为例,迁移代码如下:

add :signers, {:array, :string}, default: [], null: false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:06:04