0

E.g. :

  • Users__c --> Custom Object
  • Users__r --> Relation Object

what is the difference between Users__c and Users__r when we are using in the apex code in Salesforce?

How will i test the Users_r data in test cases ? e.g. Id id = Users_r.fk_roleId.id; // this line of code is saying that fk_roleId is not visible. so can i make this visible ?

1
  • Adding a second question after there are answers posted to the first question is best avoided.
    – Keith C
    Apr 1, 2014 at 12:01

2 Answers 2

1

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);
1
  • It's children ;)
    – pjcarly
    Apr 1, 2014 at 11:50
0

It's like 1:M or parent-child relationship in a traditional databases. One references the parent record (User__c), and the other references a list of children records (Users__r).

Parent can have many children basically and depending how you're referencing the records you use the corresponding relationship.

Account - Contacts example is given here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .