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
kalyforminkalyformin 

Triggers question

I'm quite new to Apex Triggers and I'm trying to get a solution for the below problem:

 

I have a parent object A and a child object B. There is a 1:many relationship between A and B. ie, A could have any number of Bs. I have a trigger to perform certain calculations whenever a new B is inserted or updated. What I'm trying to get is a SOQL within the trigger that will get me all B records that belong to parent A

 

SELECT age, Id, date_of_birth FROM B WHERE app_id = <id of parent object A. This exists as a master look up on object B in a field called app_id>

 

 

My question is how do we reference the id of A in the trigger to get all associated child records.

 

Any help is appreciated

SpongeBob_2009SpongeBob_2009

Create a 'Lookup Relationship' field on the child table that references the parent.  Make the field required on the layout.  This will store the ID for the parent.  Now you have a reference/path back to the parent.  Keep in mind, the Trigger object does not populate related sObjects automatically - you will get null values.  You basically need to use a collection to get around this limitation.

 

 

String qry = SELECT Id, Manager.EmployeeNumber, ... FROM User where id IN ...

 

List<SObject> outObj = Database.query(qry);

 

for (SObject inRecTmp : inSObjects)
            {  
                User inRec = (User) inRecTmp;

 

                system.debug(inRec.Manager.EmployeeNumber);

 ...

            }

 

 

 

Now use outObj, instead of a reference to the original Trigger collection.

 

 

*Always use 'Bulk' logic - work with collections.