Ecto left in right

from p in Post, where: p.id in [1, 2, 3]

if p.id is :integer it works, but if i get {:array, :integer} i get error, how i can compare two integer arrays?

Do you know what the SQL equivalent of what you want to do is? i.e. are you looking for a subset or overlap of the two arrays?

I need check all values from list in where query.

My Schema:

  schema "accounts" do
    field :groups, {:array, :integer}
  end

group = [1, 2, 3]

query = from a in Accounts, where: ^group in a.groups #i knowe, i can't pass list..

Solution is enum list, example;

query = from a in Accounts, where: ^1 in a.groups, where: ^2 in a.groups, where: ^3 in a.groups

But i don’t have any idea how do it :smiley:

query = from a in Accounts, where: fragment("? @> ?", a.groups, ^group)

4 Likes

PostgreSQL: Array Functions and Operators

3 Likes

As another option to using the postgres array functions (which will be more performant) if you instead wanted a more direct translation of your code you could incrementally build up the query using Enum.reduce:

group_ids = [1, 2, 3]
queryable = from a in Accounts
Enum.reduce(group_id, queryable, fn group_id, queryable ->
  queryable
  |> where([a], ^group_id in a.groups)
end)
2 Likes