I can't get FFLIB uow to work with a self-relationship field. Quick use case: Create two accounts and relate the second one with the first one using a custom lookup field (selfRelation__c)
fflib_ISObjectUnitOfWork uow = Application.unitOfWork.newInstance();
Account account1 = new Account();
account1.name = 'account1';
uow.registerNew(account1);
Account account2 = new Account();
account2.name = 'account2';
uow.registerRelationship(account2,Account.selfRelation__c,account1);
uow.registerNew(account2);
uow.commitWork();
and as a result, both accounts are created but the relation was not defined.
Any feedback?
Thanks
Best Answer
This isn't supported in the same Unit of Work - why?
Because both
registerNew
s are collected into a single collection ofAccount
byfflib_UnitOfWork
and inserted in a single DML statement.registerRelationship
only adjusts object references in memory - it does not do separate DML on its own.Thus, the Id for
account1
isn't yet known to set the lookupfield onaccount2
You need to do this in two units of work each with their own
commitWorks
(). That is, registerNewaccount1
in uow1, then commitWork, thenregisterNew/registerRelationship
account2 in a new instance of uow, and commitWork on that uow.Note also, the following four lines can be collapsed into one
to
as
registerNew
has an overloaded signatureWorth buying if you haven't already Salesforce Lightning Platform Enterprise Architecture by Andrew Fawcett 3rd edition (4th edition is in progress from what I hear) - page 181 Unit of Work Special Considerations