Parent objects of children...many to many

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.

Hi @David_Thompson ,
could you please clarify, do you have a circuit similar to this one, with the same relationship?

yes…pretty much identical to that one. In your example I would be trying to get a user object with all ProductOrganizations attached to the user object as an array the most efficient way possible. My way works, but it doesn’t feel right.

Hi, @David_Thompson

Since User table has no relation to ProducerOrganization, you could try to set inverted relation in selected properties to get ProducerOrganization objects Inverted Relation Retrieval

Regards,
Serhiy