Skip to content

Filtering / Sorting a Parent Resource based off its associations value #430

Description

@Reizar

I couldn't quite work out if this can be done by reading the docs / playing around with some requests.

I'm looking for a way to filter / sort a parent resource based off a child association's field.

I think an example might be the easiest way to illustrate what I'm wanting to do.

Say you have 2 graphiti resources:

class ParentResource < ApplicationResource
  self.model = Parent
  attribute :something, :string

  has_one :child, resource: ChildResource
end

class ChildResource < ApplicationResource
  self.model = Child
  attribute :other_thing, :string

  attribute :parent_id, :integer_id

  belongs_to :parent, resource: ParentResource
end

Now on the frontend, using Spraypaint to query.
What I would like to do, is something like this:

Parent.includes('child').where({'child.other_thing': 'some_value'}).all()

This will return Parents, but set the child as undefined if the other_thing value doesn't match. However what I want, is some way to exclude the parent if it can't find that child.

I understand that the easiest way to achieve this would be to flip how I query the resources and query for the child. Eg:

Child.includes('parent').where({'other_thing': 'some_value'}).all()

The reason that I want to have some way of filtering / sorting the parent based off the child, is because I have a dropdown with a whole bunch of fields that a user can choose to have their results sorted by. This includes fields from the parent and the child.

For sorting I guess I could change the resource thats queried based off the sort field. Although it does complicate the UI having to accept different models when rendering certain components.
However when it comes to filtering, there are situations where I want to stack multiple filters and that wouldn't work.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions