How to query child to parent like contact to parent..and how to query master lookup relations.
select id,lastnam,(select id,name from account where accountid=conatctid)from contact
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityHow to query child to parent like contact to parent..and how to query master lookup relations.
select id,lastnam,(select id,name from account where accountid=conatctid)from contact
This just an example on how the parent-child query works...
Ways of writing Parent - Child Queries for Standard Objects
Select Id, Name, (Select Id, LastName from Contacts where Lastname='Frank') from Account
Select Id, LastName, Account.Name from Contact
Ways of writing Parent - Child Queries for Custom Objects
Select Id, Name, (Select Id, Name from Custom_Object2s__r) from Custom_Object1__c
Select Id, Name, Custom_Object1__r.Name from Custom_Object2__c
Hope this might helps...
Select Id, LastName, (Select id, LastName from Contacts where LastName='ContactName' ) from Account
your where and from place need to be change
Jun 20, 2016 at 5:58
If you want get the parent object information then you need to use like this.
for(Contact objContact: [SELECT Id, LastName, AccountId, Account.Name FROM Contact])
{
system.debug('====Account Name======'+objContact.Account.Name);
}
if you want any other info about Account then you need to use Account.FieldAPIName... this way you will be able to get the Account info
for(Account objAccount: [SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account])
{
for(Contact objContact: objAccount.Contacts)
{
system.debug('====Contact onfo======'+objContact);
}
}
You can traverse a relationship from a child object (contact
) to a field on its parent (Account.Name
) by using dot notation.
You can traverse multiple levels upwards!
List<Contact> list= [Select ID,LastName,Account.Name, Account.Industry from Contact where Name='abcd'];
for(Contact c: list){
System.debug('Contact LastName is:' + c.LastName);
System.debug('Account Name is:' + c.Account.Name);
}
we can understand it by an example. We have Account and Contact Object and we know that the relationship between them is lookup relationship. Note : This relationship has one property called cascadedelete that is why, when you will delete a contact, it's parent will got deleted.
Child To Parent SOQL ; [ SELECT Name,Phone,Email,AccountId,Account.Name,Account.Phone,Account.BillingAddress FROM Contact ]