Getting “__r” relationship name from Schema.SObjectType.Fields

Say I have a master-detail relationship between two objects, Schematic__c and Part__c.

I can SOQL query the master from the detail: [SELECT Schematic__r.Name FROM Part__c]

If I’m building a query from strings, I resolve the schema name, for example in a managed package:

SObjectType.Part__c.Fields.Schematic__c.Name //gives me 'ns__Schematic__c'

But when traversing into the master object, the __r relationship suffix is what I need to surface. I’ve toyed around with the obvious Schema.SObjectType variations but I’m not having much luck:

SObjectType.Part__c.Fields.Schematic__r.Name //Schematic__r is not a field of ns__Symbol__c

What’s the correct way to resolve the ns__Schematic__r.Name token without replacing the suffix?

Answer

No no, the field (API) name is Schematic__c, you need to start from it. Think about Schematic__r (the rel. name) like a consistent table alias when you’d make JOINs in regular database, nothing more.

To go “up”:

Schema.DescribeFieldResult f = Schema.sObjectType.Order_Line_Item__c.fields.Order__c;
System.debug(f.getRelationshipName()); 
// Outputs "Order__r", also with namespace if you have one

(You could also play with checking f.getType() == Schema.DisplayType.REFERENCE if you need to describe all fields and wonder which ones are lookups)

to go “down”:

for(Schema.ChildRelationship cr : Order__c.SObjectType.getDescribe().getChildRelationships()){
    System.debug(cr.getChildSObject() + '.' + cr.getField() + ' reversed is: ' + cr.getRelationshipName());
}

ActivityHistory.WhatId reversed is: ActivityHistories
Attachment.ParentId reversed is: Attachments
ContentDocumentLink.LinkedEntityId reversed is: null
ContentVersion.FirstPublishLocationId reversed is: null
(...)
Order_Line_item__c.Order__c reversed is: Order_Line_items__r    // bingo
Order__History.ParentId reversed is: Histories
(...)
Task.WhatId reversed is: Tasks

Attribution
Source : Link , Question Author : Matt and Neil , Answer Author : eyescream

Leave a Comment