sort many_to_many

I thought I had asked this question before, but can't seem to find it... It seems like a very common use case, but not sure how to go about this. Is it possible to sort a many_to_many relationship based on a field in the join table. ie. if I have a Playlist:
defmodule Playlist do
relationships do
has_many :playlist_entries, PlaylistEntry
many_to_many :items, Item
end
end
defmodule Playlist do
relationships do
has_many :playlist_entries, PlaylistEntry
many_to_many :items, Item
end
end
and an Item:
defmodule Item do
...
end
defmodule Item do
...
end
And a PlaylistEntry:
defmodule PlaylistEntry
relationships do
belongs_to :item, Item
belongs_to :playlist, Playlist
end

attributes do
attribute :position, :integer
end
end
defmodule PlaylistEntry
relationships do
belongs_to :item, Item
belongs_to :playlist, Playlist
end

attributes do
attribute :position, :integer
end
end
And I want to simply load this in graphql by just adding the items:
query {
playlist {
items {
name
//ordered by position in playlist_entry
}
}
}
query {
playlist {
items {
name
//ordered by position in playlist_entry
}
}
}
I know that in graphql not all values that are not needed in the read are selected, but apart from graphQL is there a way to get this sorting happening. Thanks all!
5 Replies
ZachDaniel
ZachDaniel2y ago
You can sort the relationship in the DSL declaration, i.e sort :foo Would that suffice?
drumusician
drumusicianOP2y ago
I guess that should suffice, but where should I put it? in the many_to_many?
ZachDaniel
ZachDaniel2y ago
What you'd need to do is something like this:
has_many :links, JoinResource do
sort :foo
end

many_to_many :destination, Destination do
join_relationship :links
end
has_many :links, JoinResource do
sort :foo
end

many_to_many :destination, Destination do
join_relationship :links
end
Alternatively, if you expose the join relationship then the client can use that to sort i.e
links(sort: [....]) {
destination {
...
}
}
links(sort: [....]) {
destination {
...
}
}
drumusician
drumusicianOP2y ago
ok, cool. How does one expose a relationship?
ZachDaniel
ZachDaniel2y ago
If you split it out as shown, and give the join resource a graphql tyoe, that should do it

Did you find this page helpful?