Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unique good practise in 1:1 relationships?

In the Grails Doc: http://grails.org/doc/2.3.x/guide/GORM.html It says that adding a unique constraint in a 1:1 is good practise.
So if a face has one nose, we should do:

class Face {
    static hasOne = [nose:Nose]
    static constraints = {
        nose unique: true
    }
}

But Why? Surely, the constraint is implicit in the cardinality?

So why should we do it?

like image 413
More Than Five Avatar asked Feb 02 '26 07:02

More Than Five


2 Answers

The reason for putting the unique constraint is to ensure that two faces don't have the same nose. Since this is a 1:1 relationship the Id of the nose is kept on the face. That's why.

like image 54
Joshua Moore Avatar answered Feb 05 '26 05:02

Joshua Moore


To be sure that only one nose knows the current face.

Without this constraint :

Face face = new Face();
Nose nose1 = new Nose();
face.nose = nose1;
face.save(flush: true);

Nose nose2 = new Nose();
face.nose = nose2;
face.save(flush: true); // no error, but in DB, nose1 and nose2 reference the same face_id
like image 41
Isammoc Avatar answered Feb 05 '26 03:02

Isammoc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!