簡體   English   中英

更高級的:與苦艾酒關聯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM