Alex Antonov
Alex Antonov

Reputation: 15206

How to search for an array length in ecto

Let say I have a schema

defmodule User do
  use MyApp.Web, :model

  schema "users" do
    field :loved_numbers, {:array, :integer} 
  end
end

How could I search using Ecto.Query for all users who have exactly 2 loved_numbers?

Would this query work in both PostgreSQL and MySQL?

Upvotes: 0

Views: 1612

Answers (1)

Dogbert
Dogbert

Reputation: 222348

With PostgreSQL, you can use the array_length function using a fragment:

from(u in User, where: fragment("array_length(?, 1)", u.loved_numbers) == 2)

(The 1 is for the dimension to count, which should be 1 for one dimensional array.)

As far as I know, MySQL does not support arrays.

Upvotes: 4

Related Questions