How to filter in relationship

Hi, I have a problem that I’ve been debugging for many hours but can’t seem to solve.

I have a post resource that has comments.

post.ex

...
relationships do
    has_many :comments, Dentallog.QuestionAnswer.QuestionPostComment do
        manual Dentallog.QuestionAnswer.Relationships.CommentsHasNoParent
end
...

The comments have children and parents.

comment.ex

...
belongs_to :parent, Dentallog.QuestionAnswer.QuestionPostComment do
      attribute_writable? true
      allow_nil? true
    end

    has_many :children, Dentallog.QuestionAnswer.QuestionPostComment do
      destination_attribute :id
    end
...

When fetching comments contained in a post, I want to fetch the top-level comments and filter them by I want to filter by comments that have no parents.

manual_relationship.ex

defmodule Dentallog.QuestionAnswer.Relationships.CommentsHasNoParent do
  use Ash.Resource.ManualRelationship
  require Ash.Query

  def load(records, _opts, %{query: query, actor: actor, authorize?: authorize?}) do
    post_ids = Enum.map(records, & &1.id)

    {:ok,
     query
     |> Ash.Query.filter(question_post_id in ^post_ids)
     |> Ash.Query.filter(is_nil(parent_id))
     |> Dentallog.QuestionAnswer.read!(actor: actor, authorize?: authorize?)
     |> Enum.group_by(& &1.question_post_id)
     |> dbg}
  end
en

But when I look up the post, I don’t see anything in the comments. Any idea why?

1 Like

:wave: so, I’m not sure why your manual relationship isn’t working, but you can do this without a manual relationship :slight_smile:

relationships do
    has_many :comments, Dentallog.QuestionAnswer.QuestionPostComment do
      filter expr(is_nil(parent_id))
    end
end
1 Like

Wow that’s what I wanted, thank you~!