Elixir 更高级:与长生不老药苦艾酒协会

Elixir 更高级:与长生不老药苦艾酒协会,elixir,graphql,ecto,absinthe,Elixir,Graphql,Ecto,Absinthe,我的博客应用程序有一个Post模型,其中有许多评论 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 我也

我的博客应用程序有一个
Post
模型,其中有许多
评论

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
查询按预期工作

现在我想在
注释
模式中添加一个布尔
活动
字段,以便执行软删除;我将只选择
active==true
的注释,并通过将
active
设置为
false
来删除注释

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

field :active, :boolean, default: true, null: false
现在,我只希望苦艾酒
:comments
字段返回活动注释。我有一个自定义的解析程序

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问题。有更优雅的方法吗?

您需要在此处使用批处理解析器。报告详细解释了一切。您的查询应如下所示:

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

您需要在此处使用批处理解析器。报告详细解释了一切。您的查询应如下所示:

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