如何使用Ecto创建可组合的地方?

时间:2016-05-30 13:49:57

标签: elixir ecto

我的代码:

defmodule Model1 do
  use Ecto.Schema
  import Ecto.Query

  schema "model1" do
    belongs_to :model2, Model2
  end

  def create_query do
    Model1
    |> join(:inner, [m1], m2 in assoc(m1, :model2))
  end

  def apply_where(query, %{name: name})  do
    query
    |> where([m1, m2], ilike(m2.name, ^name))
  end
end


defmodule Model2 do
  use Ecto.Schema

  schema "model2" do
    has_many :model1, Model1
    field :name, :string
  end
end

当我尝试:

param = %{name: "test"}
Model1.create_query |> Model1.apply_where(param) |> Repo.all

它的工作正常。但是,有没有办法像这样编写apply_query函数:

def apply_where(query, %{name: name})  do
  query
  |> where([m2], ilike(m2.name, ^name))
end

如果我的查询有很多连接子句?我是否必须在列表中声明所有连接的模式(表格)(首先是arg)[m1,m2,m3,... mx]每次都绑定一个字段?

1 个答案:

答案 0 :(得分:0)

因为m2是连接中的绑定,所以您必须指定[m1, m2]。这取决于位置,而不是名称,因此您的apply_where可以[model_1, model_2],即使绑定使用不同的名称,ecto仍然会理解您的意思。

根据the docs

Bindings in Ecto are positional, and the names do not have to be consistent between 
input and refinement queries.
...
When composing queries you must specify bindings again for each refinement query.

但是,如果你有很多连接:

You are not required to specify all bindings when composing.

在你不担心连接的作品中:

Although bindings are extremely useful when working with joins, they are not
necessary when the query has only the from clause.