Trying to work with a Master-Detail relationship in apex. The following code will produce a Case with several child records, and I can use list methods to access the records (i.e. the system.debug statement produces a child record). I would like to do something like this

List<Child_Records__c> newList = c.Child_Records__r;

And add all the child records to a newList to work with the data.

However, this syntax results in the list having a size() = 0.

Case c =  [   
            SELECT Id, 
                FROM Equipment_Maintenance_Items__r 
                ORDER BY Equipment__r.Maintenance_Cycle__c ASC 
            FROM Case LIMIT 1 


Is there a short shorthand way of creating a list of child records from the parent?


The problem with these lists is that they are "magical" (i.e. they do not obey the normal rules for lists), because they are technically QueryLocator objects pretending to be normal lists. To get it the way you expect, you need to make a JSON string and then pop it back out as an object.

Case c = (Case)JSON.deserialize(
  new Map<String, Object> {
    'Id' => '500000000000000AAA', // should be a semi-real Id
    'Equipment_Maintenance_Items__r' => new Map<String, Object> {
      'size': 1,    // should match record size, or Bad Things await.
      'done': true, // if false, here be dragons.
      'records': new List<Object> {
        new Map<String, Object> {
          'Id' => 'xxxxxxxxxxxxxxx', // again, semi-real Id
          'Maintenance_Request__c' => 'somevalue',
          'Equipment__r' => new Map<String, Object> { // Related Object
            'Name' => 'Some Value',
            'Maintenance_Cycle__c' => 'Some other value',

As long as you build your object correctly, you can forge authentic-looking objects, but JSON is the only reliable way to make this work. Formulas and read-only fields may fail to populate/throw errors, so there are some limitations, but this works well for mocking many types of objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.