How to implement "entity joins" with filtering in Hot Chocolate #4106
-
Hi folks, I'm pretty new to Hot Chocolate and GraphQL, so maybe this is a really obvious or easy to answer thing (or something that does not work at all). But I couldn't find anything that answered my question in the documentation or by searching the web. So I hope you guys can give me a hand... Let's say I have a one to many relation between two entities. Let's call them "Company" and "Site". Each company can have many sites and each site belongs to exactly one company. The entities are stored in a MongoDb in collections called "companies" and "sites". The representations could for example be something like this {
//Company in collection "companies"
"_id": "4711-1234",
"name": "Example Inc."
}
{
//Site in collection "sites"
"_id": "8765-5678",
"name": "Somewhere",
"companyId": "4711-1234"
} Now I want to be able to do GraphQL queries like this: {
site {
name
company {
name
}
} or {
company {
name
sites {
name
}
} and with filtering for example {
getSites(where: { company: { id : {eq : "4711-1234"} } }) {
name
}
} or {
getSites(where: { company: { name : {startsWith: "Ex"} } }) {
name
}
} For brevity I omit the results that I would expect. I guess that's obvious. While I think I know how to accomplish a schema that can answer the first and second query, I have no clue how to do it in a way that the filtering would also work. Is that even possible? If yes, could you give an example (and maybe add it to the documentation)? Is there a limitation on how deep the graph can be that I want to query? If it is not possible, could you give me a hint how to get as close as possible to what I want to achieve? Or would the only possibility be to run my own filtering implementation? Thanks for your help... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Something like this namespace YourNameSpace
}
} In the Startup.cs class you would .AddFiltering and .AddProjections as follows -
` |
Beta Was this translation helpful? Give feedback.
-
OK, seems like I had a wrong assumption about how filtering works in Hot Chocolate. Finally @anilknarayan gave the right hint for building the schema. That is why I will accept it as an answer. But to make it work down to the database I had to change the repositories to join in the missing data. I'm not sure if that will fit my needs. But at least I have a deeper understanding of Hot Chocolate and MongoDB now. |
Beta Was this translation helpful? Give feedback.
Something like this
`
using HotChocolate;
using HotChocolate.Data;
namespace YourNameSpace
{
public class Query
{
[UseDbContext(typeof(YourDbContext))]
[UseFiltering]
[UseProjection]
public IQueryable GetSites(
[ScopedService] YourDbContext context)
{
return context.Sites;
}
}
}
}
`
Note the use of UseFiltering attribute in the …