Lookups/calcultions based on has_many relationships
I will try to be very precise and concise, so apologies if this comes off rude-ish.
- The history table contains a long list of entires that a user enters the application. Imagine like a list of chat entries.
- The users can bookmark any number of those history entries
- when retrieving a list of entries (e.g., last 40 entries, or all entries in a paged manner) I would like to try and in one go retrieve both the entries and whether they were bookmarked by this particular user
A corresponding SQL query would be something like
I have it sort of figured out with relationships and calculations, but this seems to load more data than I would actually like.
Relevant parts only:
And the bookmarks:
Continued below
12 Replies
I end up needing to load
:bookmarks
before I can calculate :is_bookmarked
:
For one resource, as above, this queries the database twice: once for history, and once for the related bookmarks.
When retrieving a list of history entries, it will once again produce to queries to the database: once for history, and once for bookmarks (seemingly retrieving all bookmarks).
Is there a way to massage Ash to produce just one query?
Thank you!So are you saying that it wouldn't let you load
:is_bookmarked
without loading :bookmarks
?
oh, yeah actually I see
thats actually a bug that its letting you do that 🙂
calculations cannot refer to relationships, only aggregates.
What I think you want here, though is a combination of exists
and a calculation argument
Ah. Brilliant. This looks exactly like what I'd want.
Only now I have no idea how to load this calculation with the arguments 🙂
load!(is_bookmarked: %{user_id: user_id})
will do it 😄
And you can filter on it like this:
Hmmm.. Something's funky 🙂
🤔 that is weird
So does that mean
Ash.Query.load(is_bookmarked: %{user_id: 1})
is returning {:error, "is invalid"}
Ah
I figured it out
argument :user_id, :uuid, allow_nil?: false
This should be :integer
because my ids are integersMakes sense, but
Ash.Query.load
should always return a query
so that might be something I need to look at
sounds pretty easily reproducible
I'll take a look in the next day or twoAnd it looks like Ash.Query returns
{:error, "is invalid"}
in this casegot it, thanks for letting me know
I'll fix it 🙂
No worries. This is brilliant anyway 🙂
Forgot to say thank you 🙂 Thank you!
no worries 😆 happy to help!