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
Kelly Logan (Raptek)Kelly Logan (Raptek) 

Create a distinct list of lookup field values given a list of detail objects where the master objects have the lookup field

I have a list of SObjects Ed, each SObject SEH is a detail to a Master SObject Student. Each Master SObject Student has a lookup field to SObject Cohort that may be null.
If it the lookup field is not null I want to record Cohort.Name, indexed by that Student. Also I want the list to be unique as multiple Ed entries may point to the same Student.

This is in a trigger so I want to do one SOQL query to create a map to use inside my main for loop. What I'm thinking is that if I can create a list (say studentList) of the Master Object (Student) Ids, I can do a single map statement that will fill from [Select Id, Cohort__c.Name From Student Where Id in :studentList]. It seems like there should be a simple way to create List<Student> studentList... directly from the list of Ed.

Best I have so far is
        map<Id, Boolean> studentMap = new map<Id, Boolean>();
        List<Id> studentList = new List<Id>();
        for (Ed__c stu : edHists) {
            if (stu.Student__c != NULL) {
                if (studentMap.get(stu.Student__c) == NULL) {
                    studentMap.put(stu.Student__c, TRUE);
                    studentList.add(stu.Student__c);
                }
            }
        }
      
        map<Id, Student> studentCohortMap = new map<Id, Student>([
            Select Id, Student__r.Name
            From Student
            Where Id in :studentList AND Cohort__c != NULL
        ]);

Is there something more efficient and/or simpler that my Friday afternoon brain is just missing?
Lars NielsenLars Nielsen
Kelly, 

Before I get into it - can you go to the Schema Builder and selected just the objects in question and attach a screenshot.
I quickly put one together but I am not sure if this is correct.User-added image
Kelly Logan (Raptek)Kelly Logan (Raptek)
Cohort Master to Contact that is Master to SEH
Kelly Logan (Raptek)Kelly Logan (Raptek)
'Student' is actually a modified Contact object. I changed the name to prevent confusion. In fact, I have to rewrite this anyway because I didn't take into account the possibility that a set of transactions handed to it might include the changes to the same student's SEHs. I was doing individual changes as necessary but I think now that I will need to be looking both in the database and in the set of updates, which makes this significantly more complicated. Seems like there should be an easier way to choose to maintain a flag on a single entry out of a related set.