Enforcing 1:1 relationship in Salesforce.com
Osama | June 3, 2010I was wondering what if I have to create a one to one relationship between two objects. There is no declarative way where we can specify a one to one relationship between two objects.
We can write a trigger to enforce a one to one relationship between two objects. The trigger can be written on the child object that validates if there is any other record with same Parent record ID. If found then instead of inserting the record, it gives an alert.
The trigger will generate a list of child objects with specified parent ID. If the list’s length that is retrieved is greater than one, it will generate an alert.
List<ChildObject> co = [select name from ChildObject where parentId = ParentId]
If (co.Size() < 2)
{
//insert
}
else
//generate alert










you can create a 1 to 1 relationship without code with a lookup.
you need a text field and tick the uniqueness checkbox.
Then a workflow will update this field by the id of the main object.
Du to uniqueness of it you will get an error message if the ‘main’ object is already linked with another
That’s the way that SF has told. I was trying to think something out of the box. cheers!
If you have a master-detail relationship you can also do a roll-up (COUNT) over the child on the master object and a validation rule that disallows this count to exceed 1.