【问题标题】:How do I filter an Ecto association with a sort如何使用排序过滤 Ecto 关联
【发布时间】:2021-05-30 01:18:14
【问题描述】:

我希望有一个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

还有一个看起来像这样的连接表:

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 字段。那是什么样子的?

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    您可以使用过滤关联,因此您可以执行以下操作:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多