For such a case, you could try to enforce data integrity on a database level but the implementation of such a constraint would mainly depend on your RDBMS (an exemple here). As far as I know, Doctrine only allows to add unique and check constraints so you will need to trust your application code to validate your entity properly before it is persisted here.
To do so, instead of UniqueEntity
, you could use the Callback
or the Expression
constraint to create your custom validation rule. Since your rule is not so complex, it would be less verbose to use @Assert\Expression
. Something like this would produce the desired result:
@Assert\Expression(
"this.getB() == null or this.getB().getSku() != this.getNum()",
message="The chosen number should not be the same as the associated number B.sku"
)
As explained in the documentation, you can attach this annotation to your class directly or you can map it to a specific field. In your example, I guess attaching it to num
would be best.