开发者

grails 1.3.7 + 2.0, section 5.2.1.1, Many-to-one and one-to-one

开发者 https://www.devze.com 2023-03-28 04:06 出处:网络
Section 5.2.1.1 has examples A - C, which seem a bit confusing: Example B:Is this still a many-to-1 relationship, like Example A (i.e. same table setup)?At the end 开发者_Python百科it says, \"to make

Section 5.2.1.1 has examples A - C, which seem a bit confusing:

Example B: Is this still a many-to-1 relationship, like Example A (i.e. same table setup)? At the end 开发者_Python百科it says, "to make a true one-to-one, use the hasOne property ...".

Example C: when hasOne is used, should belongsTo no longer be used? Is it implied?

Why do they show two variations in Example C? Is the first one prone to problems?

I'm trying to understand all the valid Many-to-1 and One-to-One combos.

Thanks


I agree their terminology is a little confusing here. But I'll try to help:

Many-to-one (A)

What they are referring to here is a relationship where the parent object points to a single child object. The child object, however, has no knowledge of the parent relationship. The reason (I believe) they are calling this a many-to-one is that a unique one-to-one mapping is not enforced. Technically, the same Nose could be used on multiple Faces just by saving them to the relationship. And, if you delete a Face, the Nose continues to exist, just without a face. (This is getting weird to write!)

One-to-one stored on the Parent table (B)

In the second example, they have added the belongsTo to enforce a one-to-one relationship. This means that the existence of a Nose depends on the existence of a Face. So, now it is a true one-to-one relationship. The foreign key for this relationship is stored on the Face table, due to the way it is configured (see the next section).

One-to-one stored on the Child table (C)

In the last example, it's still one-to-one. However, changing the simple Nose nose to static hasOne = [nose:Nose] has moved the foreign key over to the Nose table. In this case, you use the belongsTo because each Nose can only be related to a single Face.

In Summary

  • A simple assignment Model model creates a single, unidirectional relationship to the child. The child has no direct way to reference the parent relationship, and in fact, may be related to multiple parent models.
  • A bi-directional one-to-one assignment requires the child to belongTo it's parent, which also enforces data integrity through cascading.
  • A bi-directional one-to-one stored on the child is created by configuring the parent to have one (hasOne) child model.

Hopefully this helps a little. (I still think the Many-to-one terminology is awkward.)

0

精彩评论

暂无评论...
验证码 换一张
取 消