【问题标题】:More advanced :assoc with elixir absinthe更高级:搭配长生不老药苦艾酒
【发布时间】:2018-06-09 11:51:30
【问题描述】:

我的博客应用有一个 Post 模型,其中有许多 Comments。

schema "post" do
  field :title, :string
  field :content, :string

  belongs_to :owner, MyApp.Accounts.User, foreign_key: :owner_id

  has_many :comments, MyApp.Content.Comment, foreign_key: :post_id

  timestamps()
end

我也有一个相关的苦艾酒对象。

object :post do
  field :id, :integer
  field :title, :string
  field :content, :string
  field :owner, :user, resolve: assoc(:owner)
  field :comments, list_of(:comment), resolve: assoc(:comments)
end

查询按预期工作。

现在我想在 Comments 模式中添加一个布尔值 active 字段,以便我可以执行软删除;我只会选择 active == true 所在的 cmets,我会通过将 active 设置为 false 来删除 cmets。

我将该字段添加到我的架构中:

field :active, :boolean, default: true, null: false

现在我只希望苦艾酒 :comments 字段返回活动的 cmets。我有一个自定义解析器...

field :comments, list_of(:comment), resolve: fn (query,_,resolution) ->
  query =
    from c in MyApp.Content.Comment,
      where: c.post_id == ^query.id,
      where: c.active == true,
      select: c

  {:ok, MyApp.Repo.all(query)}
end

我担心这会遇到 N+1 问题。有没有更优雅的方法来做到这一点?

【问题讨论】:

    标签: elixir graphql ecto absinthe


    【解决方案1】:

    您需要在此处使用Batch Resolver。 documentation 详细解释了一切。您的查询应如下所示:

    query =
      from c in MyApp.Content.Comment,
        where: c.post_id in ^post_ids,
        where: c.active == true,
        select: c
    
    {:ok, query |> MyApp.Repo.all() |> Enum.group_by(& &1.post_id)}
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2021-10-14
      • 2018-12-03
      • 2021-07-08
      • 1970-01-01
      • 2016-02-01
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多