function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jonpilarski1.3914448382645588E12jonpilarski1.3914448382645588E12 

Query 2 unrelated custom objects in single query

Hello. I have 3 custom objects, WorkRequest, Project and ProjectRequirements. ProjectRequirements is child to Project and Project can be associated to a WorkRequest. In single query I can query data easily as such:

 requirementList = [SELECT  id, 
                            ResourceAssigned__c,
                            Project__r.Work_Request__r.Work_Request_Status__c, 
                            Status__c ,  
                            Project__r.Name, 
                            Project__r.Project_Status__c, 
                            Project__r.Work_Request__r.Name,
                            Project__r.Work_Request__r.Short_Description__c,  
                            Project__r.Work_Request__r.Problem_Description__c,
                            Comments__c,
                            Name,
                            AddRequirementDetails__c
                      FROM USD_ProjectRequirements__c
                     WHERE Project__r.Work_Request__r.Name  != null
                       AND (ResourceAssigned__c IN :idList];    

However, what I also want to do is query in single query WorkRequests assigned to a rresource which have not been related to a Project. Anywat to do this in APEX?  Basically, the equivalent of SQL UNION operator.

Thanks in advance,

Jon
EnreecoEnreeco
Hi Jon,
You want in a single query all Work_Request__c objects that are not related to any Project__c, don't you?
jonpilarski1.3914448382645588E12jonpilarski1.3914448382645588E12
HI Enreeco, Yes. A Work_Request__c might be assigned to me that is not associated to any Project__c. So a single query to retrieve it and those Project__c records assigned to me as well.

Jon
EnreecoEnreeco
You can try something like:
Select Id, (Select Id From Projects__r) From Work_Request__c
This way you have:
  • All the WR objects (assigned to you, if the assignation is done with sharing rules  or add a OwnerId filter at the end or other filter is appropriate for filtering)
  • If a WR object is not assigned to anything, you will find an empty "WR.Projects__r"  list(assuming Projects__r is the inverse relationship name for the "Work_Request__r" relation on Project__c)
  • Otherwise you'll also have all the the Proejcts related to the WR objects.
Does it make sense?