Activity › Forums › Salesforce® Discussions › How can I get the list of Junction objects in Salesforce using Apex Code?
-
How can I get the list of Junction objects in Salesforce using Apex Code?
Posted by deepika saini on April 19, 2018 at 10:37 AMHow can I get the list of Junction objects in Salesforce using Apex Code?
shariq replied 7 years, 7 months ago 4 Members · 3 Replies -
3 Replies
-
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); - [adinserter block='9']
-
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 relationshipHope this helps you. But its trick not a standard way/method.
-
Hi,
You can use Schema standard class given bu salesforce to retrieve sobjects meta data.
Hope this helps.
Log In to reply.