You need to sign in to do that
Don't have an account?
RaviKumar
Parent to Child(Account to Contact) soql query
For account there is related list of contacts. I want to know that how many contacts are there for that account.
Query should be Parent To Child like
" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Use Case: because I want to write trigger on Account and limits that for every account should not more than 3 contacts.
Thanks in advance.
Query should be Parent To Child like
" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Use Case: because I want to write trigger on Account and limits that for every account should not more than 3 contacts.
Thanks in advance.
" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Your query is right.You can access number of contacts corresponding to a specific account as below
for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
System.debug('Account name:'+a.name+' Number of contacts:'+a.contacts.size());
}
All Answers
" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Your query is right.You can access number of contacts corresponding to a specific account as below
for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
System.debug('Account name:'+a.name+' Number of contacts:'+a.contacts.size());
}
I have been trying to resolve these issue from long time. U provides an exact Solution for my Issue. I am very glad to have your reply.
And i have small clarification in that
for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
}
In the above for loop we are iterating through the QUERY "[SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]" But what if we have for loop like
for(Account a: Trigger.new){
}
In that "Trigger.new" we are not querying contacts "SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){ } "
So while I'm writing in the Trigger
for(Account a : Trigger.new){
sss.add(a.Id);
}
List<Account> aaa = [select id, name,(Select id from Contacts) from Account where id in: sss ];
for(Account a : aaa){
If(a.contacts.size() <= 3 ){
}
}
Is ther any way to reduce the code.
Once again Thank u for your information.....
List<Account> aaa=[select id,name,(select id from Contacts) from Account where id in :trigger.newMap.keySet()];
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables.htm