[英]More advanced :assoc with elixir absinthe
My blog app has a Post
model that has many Comment
s. 我的博客应用程序具有一个Post
模型,其中包含许多Comment
。
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
I have an associated absinthe object as well. 我也有一个相关的苦艾酒对象。
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
Queries work as expected. 查询按预期工作。
Now I want to add a boolean active
field to the Comments
schema so that I can perform soft deletes; 现在,我想向Comments
模式添加一个布尔active
字段,以便可以执行软删除。 I'll only select comments where active == true
, and I will delete comments by setting active
to false
. 我只选择active == true
注释,并且将active
设置为false
来删除注释。
I add the field into my schema: 我将字段添加到我的架构中:
field :active, :boolean, default: true, null: false
Now I only want the absinthe :comments
field to return active comments. 现在,我只希望苦艾酒:comments
字段返回活动评论。 I have a custom resolver for this... 我为此有一个自定义解析器...
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
I'm worried this is going to run into an N+1 problem though. 我担心这会遇到N + 1问题。 Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点?
You need to use a Batch Resolver
here. 您需要在此处使用Batch Resolver
。 The documentation explains everything in detail. 该文档详细解释了所有内容。 Your query should look like the following: 您的查询应如下所示:
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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.