I have two objects:


Patient has many inquiries so there is a lookup field on the inquiry object.

now here is my code:

Patient__c p = [Select Id from Patient__c where id='00QJ000000B4yXa'];
SObject container;
Schema.sObjectType sType = Schema.getGlobalDescribe().get('inquiry__c');
container = sType.newSObject();

I need a way to get the name of the lookup field on the child object .

in this example I would need the patient__c fieldname on the child record

3 Answers 3


You could use the SObject's getDescribe method (from the parent object), then call the DescribeSObjectResult's getChildRelationships() method. This will give you a list of Schema.ChildRelationship entries, each one providing the name (getRelationshipName) you'd use to query with, and the field (getField) that is the lookup field on the child object (it's an SObjectField, so you may need to run a describe on it if you need more information.

SObjectField parentField;
for(ChildRelationship rel: Patient__c.SObjectType.getDescribe().getChildRelationships()) {
    if(rel.getChildSObject() == Inquiry__c.SObjectType) {
        parentField = rel.getField();
// Here, parentField is the Inquiry__c's lookup field to Patient__c
  • Damn, looks like you beat me to it :P Mar 11, 2016 at 19:17

You can use the describe for Patient__c to get the child relationships, and loop through them until you find the one for Inquiry__c and get the field name from that like so:

for(Schema.ChildRelationship relation : sObjectType.Patient__c.getChildRelationships()){
    if(relation.getChildSObject() == Inquiry__c.sObjectType ){
        FieldTokenYouWant = relation.getField();

Here is one way to do that starting from the child side using the Contact object as an example:

SObjectType t = Contact.SObjectType;
for (SObjectField f : t.getDescribe().fields.getMap().values()) {
    if (f.getDescribe().getType() == DisplayType.Reference) {
        System.debug(f + ' is a lookup');

See the DescribeFieldResult documentation for more detail on the field information that is available.

If you know the parent object (as you appear to) sfdcfox's approach is better.

(Incidentlly this describe API feels a bit strange in this area in that you declare the dependency at the child side but the parent-side has the more convenient API i.e. there is no getParentRelationships method.)

You must log in to answer this question.

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