I have custom object People__c
that has lookup field Married__c
to the same object (People__c
) and I want to create a trigger for auto update after insert and update. For example, if we insert new People__c
(husband) or modify it and add in lookup field another People__c
(wife) then wife must have in her lookup field automatically added husband and conversely.
I've written the next code but it doesn't work. What could I try instead?
trigger InsertUpdateMarried on People__c (after insert, after update) {
Set<Id> peopleMarriage = new Set<Id>();
for(People__c people : trigger.New) {
peopleMarriage.add(people.Married__c);
}
Map<Id,People__c> matchingPeopleMap = new Map <Id,People__c>();
for (People__c people : [Select Id, Married__c From People__c Where Id IN :peopleMarriage]) {
matchingPeopleMap.put(people.Id, people);
}
List<People__c> peoplesToUpdate = new List<People__c>();
for(People__c people : trigger.New) {
if (matchingPeopleMap.containsKey(people.Id))
{
people.Married__c = matchingPeopleMap.get(people.Id).Id;
peoplesToUpdate.add(people);
}
}
update peoplesToUpdate;
}