[SalesForce] Complicated Query with many subqueries

So I have a rather complicate query that I am trying to do all in one step which may or not be possible

To try and explain I have custom objects called "paths" and paths are specialized content available for specific types of users tied to specific "actions" which are our main content. Theres two other custom objects. Path Groups (which is just a master detail with paths) and then (Path Group Permissions) which is what grants permission to accounts to specific paths..

An example might help

So we have a path group called Homeownership, this path contains many little bits of info (called paths)… and then certain portal users can see this information so they have a path group permission on their account record

So the question is, my visualforce page is looping through all the actions and I want it to also display any paths available to the user.

This bit of code is working now:

string userId = UserInfo.getUserId();
User u = [select ContactId, Email, FirstName, LastName, Title 
          from User where Id=:userId];

Contact c = [select id, AccountId, Contact.Account.Name, Contact.Account.Id
             from Contact where id = :u.ContactId];

List<Path_Group_Permission__c> pgp = [select Path_Group_Permission__c.Path_Group__r.id 
    from Path_Group_Permission__c
    where Path_Group_Permission__c.Account__r.Id = :c.Account.Id];

Actions =  [Select Name, body__c, Action_Type__c, Caution__c,  URL_Title__c, 
    (select Path__c.Id, Path__c.Name, Path__c.Body__c from Action__c.Paths__r
        where Path__c.Path_Group__c = :pgp[0].Path_Group__r.id)
    from Action__c order by Order__c ];

the problem is its only checking the first "PGP" or path group permission. I feel like I should be able to use "IN" to check all of them but I am not having any luck

I tried

  • Path__c.Path_Group__c IN :pgp
  • Path__c.Path_Group__c IN :pgp.Path_Group__r.id
  • and adding the pgp query into the actions query like Path__c.Path_Group__c in **subquery**

no luck… any ideas?

Best Answer

Iterate over the pgp list and accumulate all the path group ids in a List and then use this as the predicate for an IN condition

List<Id> pgIds = new List<Id>{};
For (Path_Group_Permission__c pgperm : pgp)
pgIds.add(pgperm.Path_Group__r.id);

And then use the collection in the Where

where Path_c.Path_Group__c IN :pgIds

As an aside you're not filtering on Actions, so could there be Action records which don't have associated Path records?