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
Glenn DalyGlenn Daly 

Preventing duplicate records on a junction object with 3 lookup fields.

I have two fields on a junction object that look up to the account object. One is called "Member Account" the other "Group Account". If Account A = Member Account, and Account B = Group Account then Account A shouldn't be able to be a Group Account if Account B is a Member Account.
I realise that I can't enforce this with a validation rule, so was thinking along the lines of creating another field, making it unique, and updating it with the values of two fields combined, but that probably won't work either.
Any ideas on how I can prevent this happening?
Key point here is that if Account A = "Group Account" and Account B = "Member Account" then Account A can never be "Member Account" if Account B = "Group Account" on another record within the junction object.
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Dear Glenn,

A small apex trigger can prevent this using external id field to maintain uniquiness.

Regards
Ashish
ashish.sharma.devsfdc@gmail.com
Glenn DalyGlenn Daly
Thanks Ashish

I'm completely new to writing triggers. Would you mind checking if I'm along the right lines below?

I guess it's going to be a before insert trigger on the junction object.

Then I'll need to get all of the records of the junction object using a SOQL query and put them into a list/map?

I'll then need to write some kind of logic. (can you help with this please?)

Put the records back into a list and insert them into the database?
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Dear Glenn,

In trigger ,we have out of box provided collections i.e. trigger.new ,trigger.old which will hold all the records for your junction object .

Please go through below trailhead to get start with trigger .

https://developer.salesforce.com/trailhead/en/apex_triggers/apex_triggers_intro

Regards
Ashish
ashish.sharma.devsfdc@gmail.com
Dustin NordquistDustin Nordquist
Since spring 20, we can use Before Save Flow to concatenate the IDs into a text field that we can then prevent duplicate junction object records. Details: https://goravseth.com/preventing-duplicate-junction-object-records