Relationships between objects are formed by the child object having a field that contains the ID of the parent object. By default this field has the same name as the parent object, and if it is custom objects that are involved it will therefore end in __c
. In the Setup UI these fields are the ones of type "Lookup Relationship" or "Master-Detail Relationship".
But as part of the syntax of SOQL and as a convenience to the programmer, the platform also automatically makes available some extra fields that end in __r
. These fields don't hold an ID, but instead can hold a reference to the (single) parent object when they are located in the child object, and to the (possibly many) child objects when they are located in the parent object. When creating data models, it is helpful to use singular names and plural names appropriately for these. But these fields are only populated when both the parent and child have been queried together and are not populated in for example triggers.
With Parent__c
and Child__c
custom objects:
Parent__c p = [
select Id, Name, (select Id, Name from Childs__r)
from Parent__c
where ...
];
// p.Childs__r is a list of Child__c object references
for (Child__c c : p.Childs__r) {
// c.Parent__c is the same as p.Id
// c.Parent__r is the same as p (a reference to a Parent__c object)
}
// And to add an extra Child__c:
insert new Child__c(Parent__c = p.Id);