I have three tables: User, ProducerProfile and ProducerOrganization. ProducerProfile is like an association table/junction table because User has a one to many relationship with ProducerProfile and ProducerOrganization has a one to many with ProducerProfile as well. When I run a query to load the User I’d like to also load their associated ProducerOrganization(s), but getting them through the ProducerProfile relationship seems a bit tricky since ProducerProfile is a child of ProducerOrganization. Here is what works, but it seems like I have overcomplicated it. Is there a better way?
The part that seems particularly nasty to me is the mapping into a string for the subquery. This just feels wrong.
// first get User with relations
let query = Backendless.DataQueryBuilder.create().setRelationsDepth(1);
Backendless.Data.of('Users').findById(userId,query)
.then( (userAndRelations) => {
// then map related objectId's into something BE can use for a subquery (ugh)
let prodIds2 = `( ${userAndRelations.producerProfiles.map(obj => `'${obj.objectId}'`).join(', ')} )`
let q2 = Backendless.DataQueryBuilder.create();
let wc = `producerProfiles.objectId IN ${prodIds2}`;
q2.setWhereClause(wc);
Backendless.Data.of("ProducerOrganization").find( q2 )
.then( (prodOrgs) => {
userAndRelations.producerOrgs = prodOrgs;
console.log(prodOrgs);
})
.catch( (error) => {
console.log(error);
})
})
.catch( (error) => {
console.log(error);
})
I’m mostly trying to find the simplest way to get all parent object of an array of children objects without looping.