Search code examples
elixirecto

How to use ANY operator with array field with Ecto?


How to find all posts with a tag 'apple' ?

  schema "posts" do
    field :title, :string
    field :content, :string
    field :tags, {:array, :string}

    timestamps()
  end

With postgresql it would be:

SELECT title FROM posts WHERE 'apple' = ANY(tags);


Solution

  • You will want to use Ecto's in/2 operator. The second example for that function is exactly what you want.

    MyApp.Repo.all(from post in MyApp.Posts, where: ^"apple" in post.tags)