1

我的博客应用程序有一个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

查询按预期工作。

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

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

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 问题。有没有更优雅的方法来做到这一点?

4

1 回答 1

3

你需要在Batch Resolver这里使用。该文档详细解释了所有内容。您的查询应如下所示:

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)}
于 2017-12-29T02:59:05.067 回答