How to force UNIDIRECTIONAL to-many relationship to persist

前端 未结 3 1926
無奈伤痛
無奈伤痛 2021-01-06 17:25

There is a problem with core data when a to-many relationship has no inverse. Changes made to the related property do not persist. This is a problem many of us have faced, a

3条回答
  •  天涯浪人
    2021-01-06 17:50


    This is a great question.

    ButFirst thing first:
    It clearly state in the documentation:

    "Important: You must define many-to-many relationships in both directions—that is, you must specify two relationships, each being the inverse of the other. You can’t just define a to-many relationship in one direction and try to use it as a many-to-many. If you do, you will end up with referential integrity problems."

    Never the less, Lets describe the issue (resulting database)
    When defining a to-many relationship, the resulting database does not add an additional table to map the relationship.
    It only sets a property on the entity at one end of the to-many relationship equal to the last item that referenced it.

    Example:

    Model:
    Entity: Department
    Relationships: NONE
    Properties: name (string)

    Entity: Employee
    Relationships: departments (to-many,no-action)
    Properties: name

    Resulting Database:
    ZDEPARTMENT:
    Z_PK
    Z_ENT
    Z_OPT
    Z2DEPARTMENTS (int)
    ZNAME

    ZEMPLOYEE:
    Z_PK
    Z_ENT
    Z_OPT
    ZNAME

    This structure will obviously result in data inconsistency.

    The solution will be to hold an entity: DepartmentEmployee modeling the to-many relationship in both directions but one of them would be unidirectional (Department -> DepartmentEmployee):

    DepartmentEmployee:
    Relationships: department (to-one,no-action), employee (to-one,nullify)

    and you will have to maintain the table upon deletion of a department object.

    Hope this made some sense :)

提交回复
热议问题