Thanks Zach! That makes sense. In my test I wasn’t returning any posts in the response which is why I wasn’t seeing the subsequent request for the comments.
So, this way of handling relationships makes total sense for a relational database model where the resource on the “belongs to” side of a “has many” relationship has a foreign key pointing back at the parent record. Unfortunately Sanity stores their data in a NoSQL data lake where the parent resource keeps a reference to all the related resources so when you query for a list of posts you get something back like the following:
[
{
_id: "7d10669d-7e9f-4c8c-a7db-e1ea369e7055",
_type: "post",
title: "My First Post",
body: "A very thought provoking post",
comments: [
{
_key: "13ad3eba8563",
_type: "reference",
_ref: "1ccb9a37-c0f2-4aa7-82cb-3e16e6ecab99"
},
{
_key: "d8c1e6a53174",
_type: "reference",
_ref: "fff10398-7cb1-4d9f-8dfd-42d0f8aca798"
},
{
_key: "6faf4ddeef52",
_type: "reference",
_ref: "a7e06b12-561e-4ad8-9756-cd1979e754be"
},
]
},
… (more posts)
]
If you want to load/dereference the comments you would do so when you query for the Posts or you’d have to look at the IDs in the comments array then do a query like id in [...]
on the comment resource. I’ve been trying to figure out what the best way would be to model something like that using Ash resources and at this point I have two thoughts:
- Create a custom
ref
type for the comments attribute. Something like:
attributes do
attribute :comments, {:array, ref: Comment}
end
I’d then need to handle that attribute type when casting attributes in my DataLayer which probably isn’t ideal.
- Create a new
references
block on resources that use AshSanity which could look something like:
references do
has_many :comments, Comment
end
This approach feels like the more idiomatic way to do it but may involve touching a lot of plumbing and figuring out how to add support to Ash.Query
so it knows how to load those references.
It may also just be the case that the Ash DataLayer model isn’t a good fit for modeling a NoSQL data store and I’m just totally barking up the wrong tree.
Would love to get your thoughts.