+ Start a Discussion
Lakshmi SLakshmi S 

SOQL query for 3 level relation ship?

Hi Team,

Q). I have a 3 Objects A,B,C.
Object A is the parent of B, Object B is the parent of C.
How can we get the data from all three objects using single SOQL Query ?


Thanks in Advance..............
Regards
Lakshmi.
 
Best Answer chosen by Lakshmi S
NArendra NimmanaNArendra Nimmana
Hi Lakshmi,
You can use the below query
List<user_three__c> usre3=[select id,name,user_two__r.name,user_two__r.user_one__r.name from user_three__c];
system.debug(usre3[0].name);
system.debug(usre3[0].user_two__r.name);
system.debug(usre3[0].user_two__r.user_one__r.name);

i have tested as well it is working fine.

All Answers

NArendra NimmanaNArendra Nimmana
Hi lakshmi,
no way you can do it from parent to child(i.e,. A to C), but you can do it in reverse order(as C to A).

considering all are custom objects and  having 'name' as a Field( and B__c is a lookup field in C to B, A__c is lookup field in B to A) and C__c is a custom object. You can do it as the following way
select name,B__r.name,B__r.A__r.name from C__c
Nagaraju salesforceNagaraju salesforce
Hi Lakshmi,

I think you have completed this task.

Regards,
Nagaraju
Lakshmi SLakshmi S
HI Narendra,

Thanks for your reply.
It's not working.
NArendra NimmanaNArendra Nimmana
Hi Lakshmi,
can you provide me the object Api name's , relationships and fields(Api names) you want to revieve.
so that i can tell you clearly.
Thanks.
Lakshmi SLakshmi S
Hi Narendra,

There are three objects called user_one__c, user_two__c, user_three__c.
user_one__c fields -- > name
user_two__c fields --- > name,user_one__c (lookup field and relation ship name both are same)
user_three__c fields ---> name,user_two__c (lookup field and relation ship name both are same)

user_one__c is the parent object for user_two__c
user_two__c is the parent object for user_three__c

Now, i want to fetch name data from all three objects using single soql query.
NArendra NimmanaNArendra Nimmana
Hi Lakshmi,
You can use the below query
List<user_three__c> usre3=[select id,name,user_two__r.name,user_two__r.user_one__r.name from user_three__c];
system.debug(usre3[0].name);
system.debug(usre3[0].user_two__r.name);
system.debug(usre3[0].user_two__r.user_one__r.name);

i have tested as well it is working fine.
This was selected as the best answer
Lakshmi SLakshmi S
Hi Narendra,

Thanks for your reply.