function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek AS 3Abhishek AS 3 

Retrieve accounts related to contacts whose contact name contains word 'test'

I have a requirement in which i have to retrieve accounts related to contact where contact name matches the keyword entered by user.
string keySearch = '%' + 'T' + '%';
        List<Contact>conList=[SELECT Name,AccountId FROM Contact WHERE Name LIKE: keySearch];
        List<Account>accList= new List<Account>();
        for(Contact con: conList){
            if(con.AccountId!=null){
                accList=[Select id,Name, Industry From Account where id =: con.AccountId];
                
            }
            
        }
system.debug(conList);
system.debug(accList);
Its not working properly
Best Answer chosen by Abhishek AS 3
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhishek,

Can you try the below logic.
 
string keySearch = '%' + 's' + '%';
        List<Contact>conList=[SELECT Name,AccountId FROM Contact WHERE Name LIKE: keySearch];
Set<Id> accountids= new Set<Id>();        
List<Account>accList= new List<Account>();
        for(Contact con: conList){
            accountids.add(con.accountid);
            }
            
  accList=[select id,Name from Account where id in :accountids];      
system.debug('sasas'+accList);
Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

You need the Accounts whose contact name is like searchkey?

Thanks,
 
Abhishek AS 3Abhishek AS 3
Yes Get Outlook for Android
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhishek,

Can you try the below logic.
 
string keySearch = '%' + 's' + '%';
        List<Contact>conList=[SELECT Name,AccountId FROM Contact WHERE Name LIKE: keySearch];
Set<Id> accountids= new Set<Id>();        
List<Account>accList= new List<Account>();
        for(Contact con: conList){
            accountids.add(con.accountid);
            }
            
  accList=[select id,Name from Account where id in :accountids];      
system.debug('sasas'+accList);
Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
 
This was selected as the best answer
Abhishek AS 3Abhishek AS 3
Its working Get Outlook for Android