27

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?

  • I can see a feature within the Field Sets offering that gets me close: 1. go to the Part__c object and create a new Field Set, 2. drag Part Name and Schematic Name into the Field Set, 3. exec SObjectType.Part__c.FieldSets.MyFieldSetName.fields[1].FieldPath which gives ns__Schematic__r.Name, but Field Sets are subject to removal and rearrangement etc. – bigassforce Jan 5 '14 at 1:08
25

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
  • 8
    Now we're cooking with gas! And I can evaluate these in Visualforce too: $ObjectType.Part__c.Fields.Schematic__c.RelationshipName – bigassforce Jan 5 '14 at 12:11

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.