Activity Forums Salesforce® Discussions How can I get the list of Junction objects in Salesforce using Apex Code?

  • Aman

    Member
    April 20, 2018 at 5:54 am

    Hi Deepika ,

    you cannot query the list of junction objects using apex code but what you can do is query all the Sobjects  using the schema class, below is the code to do :

    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
    system.debug('gd:::::'+gd);

  • PRANAV

    Member
    April 20, 2018 at 9:13 am

    Hi Deepika,

    You can't get the list of junction object directly, but you can use the below code snippet for finding that this object has master-detail relationship or not. Its a trick if you have junction object with two master-detail relationship. As a junction object is a custom object with two master-detail relationships, and is the key to making a many-to-many relationship{as per standard}.

    Map<String, SObjectField> mapLeadFieldAPIToSchema = Lead.getSObjectType().getDescribe().fields.getMap();
    for(String fieldName : mapLeadFieldAPIToSchema.keySet()){
    SObjectField field = mapLeadFieldAPIToSchema.get(fieldName);
    if(field.getDescribe().getRelationshipOrder() == 0){
    //the variable fieldName contains the name of a field which is the parent of a master-detail relationship
    system.debug('@@@@'+fieldName);
    }
    if(field.getDescribe().getRelationshipOrder() == 1){
    //the variable fieldName contains the name of a field which is the parent of a master-detail relationship
    system.debug('@@@@'+fieldName);
    }
    }

    You should use the getRelationshipOrder() method available in the DescribeFieldResult class. This is populated only for Master-Detail relationships and is null for lookup relationships. Also, to get the name of the Master Object, you need to use the getReferenceTo() method.

    RelationShipOrder : The type of relationship for a master-detail relationship field. Valid values are:

    0 if the field is the primary relationship
    1 if the field is the secondary relationship

    Hope this helps you. But its trick not a standard way/method.

  • shariq

    Member
    September 20, 2018 at 6:49 pm

    Hi,

    You can use Schema standard class given bu salesforce to retrieve sobjects meta data.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos