如何过滤 Ecto 与排序的关联

How do I filter an Ecto association with a sort

我希望在连接我的多对多关联的联接 table 上通过排序字段过滤 has_one

我有两个模式:

schema "thing1" do
  field :name

  many_to_many :thing2, Thing2, join_through: "thing1_thing2"
end

schema "thing2" do
  field :name

  many_to_many :thing1, Thing1, join_through: "thing1_thing2"
end

还有一个连接 table 看起来像:

schema "thing1_thing2" do
  field thing1_id
  field thing2_id
  field created_date, :utc_datetime
end

我想在 thing1 上添加一个 has_one,由 created_date 自动订购。也许它看起来像这样:

schema "thing1" do
  ...
  has_one :oldest_thing2, Thing2, through: [:created_date, :desc]
end

这样的事情可能吗?我知道过滤关联是但不确定这些过滤器可以做什么。

另一个选项可能是在我可以过滤的关联上有一个 boolean 字段。那看起来像什么?

您可以使用过滤后的关联,这样您就可以执行以下操作:

schema "thing1" do
  ...
  has_one :filtered_thing2, Thing2, where: [flag: true]
end

但我认为 ecto 目前还不支持有序关联。如果您需要对关联进行排序和过滤的组合,您可以借助可组合查询编写自定义函数。

defmodule Thing1 do
  schema "thing1" do
    ..
    has_one :filtered_thing2, Thing2, where: [flag: true]
  end

  def custom(query)
    from c in query,
      order_by: [desc: c.created_at]
  end
end

然后您可以使用它并查询:

assoc(thing1, :filtered_thing2) |> Thing1.custom() |> Repo.all()