I have a parent and child with lookup relation and I want the child to get deleted automatically when parent is deleted. How to write a trigger for this situation
Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
For Standard Object:
trigger DeleteConWhenAccDeleted on Account (before delete) {
List<Id> accIds = new List<Id>();
for(Account acc : trigger.old) {
accIds.add(acc.Id);
}
//Collect all child records related to Parent records
List<Contact> child = [SELECT Id FROM Contact WHERE AccountId IN :accIds];
//Delete child records
DELETE child;
}
For Custom Object:
trigger DeleteChild on Parent__c (before delete) {
List<Id> ParentIds = new List<Id>();
for(Parent__c p : trigger.old) {
ParentIds.add(p.Id);
}
//Collect all child records related to Parent records
List<Child__c> child = [SELECT Id FROM Child__c WHERE Parent__r.Id IN :ParentIds];
//Delete child records
DELETE child;
}
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Greetings to you!
Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
For Standard Object:
For Custom Object:
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Thanks and Regards,
Khan Anas