How to extract first element from `many_to_many`

I have a many_to_many relationship and i want to get the first element from it. I have also a has_many relationship and can get the first element using has_one with from_many? but this is only the "merging" Resource. Is there something similar for many_to_many ? I can't use calculations or aggregations, because they can't return a resource so has_one seems to be the only one left.
5 Replies
barnabasj
barnabasj2mo ago
You can use a has_one with a filter using parent
Rise
RiseOP2mo ago
This works, when I use the has_many as the basis inside of the filter and ignore the many_from_many I am a bit confused though how to sort the has_many since it is the "merging" resource. I found this in the docs
many_to_many :tags, MyDomain.Tag do
through MyDomain.PostTag
join_relationship :post_tags
sort [calc(parent(post_tags.position))]
end
many_to_many :tags, MyDomain.Tag do
through MyDomain.PostTag
join_relationship :post_tags
sort [calc(parent(post_tags.position))]
end
In the example from the website how would get largest city by population that is stored inside of the city if the parent is a "merging" table
barnabasj
barnabasj2mo ago
I was thinking something along the lines of
has_one :first_tag, Tag do
no_attributes? true
from_many? true
filter(exists(post_tags, post_id == parent(id)))
sort [calc(first(post_tag, field: order, query: [filter: expr(post_id == ^parent(:id))]))]
end
has_one :first_tag, Tag do
no_attributes? true
from_many? true
filter(exists(post_tags, post_id == parent(id)))
sort [calc(first(post_tag, field: order, query: [filter: expr(post_id == ^parent(:id))]))]
end
The sort is a bit tricky, and I'm not 100% sure if it compiles, not on a machine with elixir atm
Rise
RiseOP2mo ago
Thank you! I will try it out Also i saw in another chat that you can do something like this:
list_tags(load: [tags: Ash.Query.sort(field: :desc)]
list_tags(load: [tags: Ash.Query.sort(field: :desc)]
maybe there is a way to stuff similar thing into the has_many or into calc

Did you find this page helpful?