You can get the kind of relationship query you required using inner describes.
Each Schema.SObjectField
is having a method called getReferenceTo()
which return List<Schema.SObjectType>
if the Schema.SObjectField
is a reference field. So using this we can determine whether the field is a relationship field or not and if it is, we can do inner describe to get the fields of the relationship object.
I just added single level of inner describe to the code snippet of yours.
public Contract con {get;set;}
ConId=ApexPages.CurrentPage().getParameters().get('ConId');
Map<String,Schema.SObjectType> fMap = Schema.getGlobalDescribe();
fieldMap = fMap.get('Contract').getDescribe().fields.getMap();
if (fieldMap.size() > 0){
for(Schema.SObjectField sfield : fieldMap.Values()){
if(Str == null)
Str = sfield.getDescribe().getname();
else
Str += ','+sfield.getDescribe().getname();
if(sfield.getDescribe().getReferenceTo() != NULL && sfield.getDescribe().getReferenceTo().size() == 1) {
fieldMap1 = sfield.getDescribe().getReferenceTo()[0].getDescribe().fields.getMap();
if (fieldMap1.size() > 0){
for(Schema.SObjectField sfield1 : fieldMap1.Values()){
if(Str == null)
Str = sfield.getDescribe().getRelationshipName() + '.' + sfield.getDescribe().getname();
else
Str += ','+Str = sfield.getDescribe().getRelationshipName() + '.' + sfield.getDescribe().getname();;
}
}
}
}
}
string query = 'Select '+ Str +' from Contract where id =: ConId';
con = database.query(query);
This will query all of the fields of the relationship fields in Contract
object. You could just check for the Account
object and execute the inner describe only for that object.
Hope it helps.