[SalesForce] How to delete child object in Lookup relationship

I am having a doubt in Salesforce.

I know the difference between Look up and master-detail relationship in Salesforce.

But Suppose I am having a scenario, where I am having 2 object with look up relationship.
I want that on deletion of parent object, the child object automatically be deleted.

How I will achieve this?

Please remember here the relation is lookup.

Regards

Best Answer

If its a lookup you will need a simple trigger to do this in real time

trigger onParentObjectDelete on CustomObject__c (before delete){
List<Id> idsToQuery = new List<Id>{};
for(CustomObject__c a: Trigger.old){
    idsToQuery.add(a.id);
 }

//query all child records where parent ids were deleted
ChildObject__c[] objsToDelete = [select id from ChildObject__c where ParentId__c IN :idsToQuery];

delete objsToDelete; //perform delete statement
}

This is if you are planning to do a real time delete .Also in this case be sure to check with business what if someone undeletes a record from the bin.May be a trigger to handle this as well

Also if you don't need a real time delete ,a batch process to fetch orphaned childs(ParentId is null) and delete .