[英]More advanced :assoc with elixir absinthe
我的博客應用程序具有一個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
我也有一個相關的苦艾酒對象。
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
注釋,並且將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問題。 有沒有更優雅的方法可以做到這一點?
您需要在此處使用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)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.