Search code examples
ectoelixir

Ecto 'where and where' clause


I want to select a single record (the whole record) where the name is xxx and the brand is xxx. The record will always be singular because name and brand are a unique index:

  def getProductByNameAndBrand(name, brand) do
    IO.puts("getProductByNameAndBrand")
    IO.inspect(name)
    IO.inspect(brand)
    from p in Api.Product, 
    where: [name: ^name], 
    where: [brand: ^brand]
    select %{id: p.id, name: p.name, brand: p.brand}
  end

This is throwing:

== Compilation error on file lib/api/repo.ex ==
** (CompileError) lib/api/repo.ex:278: undefined function p/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

I prefer this kind of syntax:

  def getProductByNameAndBrand(name) do
    Api.Product |> Ecto.Query.where(name: ^name) |> all
  end

However not sure if it can be done in that style?

What am I doing wrong?

EDIT: Pretty sure this is working in the desired manner but will post here as still verifying that it has no bugs:

  def getProductByNameAndBrand(name, brand) do
    Api.Product |> Ecto.Query.where(name: ^name) |> Ecto.Query.where(brand: ^brand) |> all
  end

Solution

  • In your query written in query syntax after second where, you missed the comma. Rest of your code looks fine. In newest Ecto versions you have also or_where if you would like to apply OR clauses instead of AND for where expressions.