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
SFDC12SFDC12 

help on query

Hi everyone, i need to fecth account related contacts which has only attachments ,please help me out

Thanks in Advance.
mukesh guptamukesh gupta
Hi,

Please use below code:-
 
List<id> conIds = new List<id>();

for(Account acc:[SELECT ID,(SELECT id,name FROM Contacts) FROM Account where id =: accountID]){

	for(Contact con : acc.Contacts){
	   conIds.add(con.Id);
	}
}


Set<Id> contWithAttachment = new Set<Id>();

Map<Id,Attachment> attachments = new Map<Id,Attachment>([SELECT Id,name,ParentID FROM Attachment WHERE ParentID IN: conIds]);

for(Attachment a : Attachments){

contWithAttachment.add(a.ParentID);

}

List<Contact> conList = [Select Id,Name from Contact where Id IN: contWithAttachment];

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
mukesh guptamukesh gupta
Hi 

Please use updated code:-
 
List<id> conIds = new List<id>();

for(Account acc:[SELECT ID,(SELECT id,name FROM Contacts) FROM Account where id =: accountID]){

	for(Contact con : acc.Contacts){
	   conIds.add(con.Id);
	}
}


Set<Id> contWithAttachment = new Set<Id>();

Map<Id,Attachment> attachmentMap = new Map<Id,Attachment>([SELECT Id,name,ParentID FROM Attachment WHERE ParentID IN: conIds]);

for(Attachment a : attachmentMap.values()){

contWithAttachment.add(a.ParentID);

}

List<Contact> conList = [Select Id,Name from Contact where Id IN: contWithAttachment];

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
AnkaiahAnkaiah (Salesforce Developers) 
Hi,

try with below code.
 
set<id> conids = new set<id>();
    
    for(contact conlist:[select id from contact where accountid='xxxxxxxxx']){
      conids.add(conlist.id); 
    }
set<id> attachementconids = new set<id>();
for(attachment attachments:[SELECT Id,name,ParentID FROM Attachment WHERE ParentID IN: conids]){
 attachementconids.add(attachments.parentid);  
    
}

List<contact> conlist = [select id,name from contact where id=:attachementconids];

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​