I'm working with a code that has an embeds_many
like this:
defmodule People do
(...)
schema "people" do
embeds_many :addresses, Address
end
(...)
end
defmodule Address do
(...)
@primary_key {:id, :binary_id, autogenerate: false}
embedded_schema do
field :type, :string
end
(...)
end
A typical value for addresses would be:
addresses: [
%Address{
id: "123",
type: "home"
}
]
How can I query all people that have addresses with id = 123
and type = home
?
EDIT: As suggested, I've tried:
query =
from p in People,
where: fragment(
"? <@ ANY(?)",
~S|{"id": 123, "type":"home"}|,
p.addresses
)
Repo.all(query)
And I get this error
** (Postgrex.Error) ERROR 42809 (wrong_object_type): op ANY/ALL (array) requires array on right side
EDIT: This error was due to a wrong definition of the field in the migration.
It was defined as a map
, and according to embeds_many documentation it should be {:array, :map}
One might use fragment
and internal PostgreSQL capabilities:
query =
from p in People,
where: fragment(
"? <@ ANY(?)",
~S|{"id": 123, "type":"home"}|,
p.addresses
)
Repo.all(query)