Deletions in a many-to-many structure

后端 未结 3 689
孤城傲影
孤城傲影 2021-02-12 11:17

I just want to check really quickly. Say I have two entities in a data model: Catalog, and Product. They have a many-to-many relationship with each other, and both are require

相关标签:
3条回答
  • 2021-02-12 11:55

    Nullify is sufficient, and many-to-many sounds right. The specific constraint you want (deleting orphans) is not directly enforceable by core data, though, so you get to do a little cleanup yourself.

    Specifically, implement willSave in your entity classes, and have each entity test: am I not deleted; and, do I have no associated (products/catalogs)? If so, delete myself. (the not-deleted test is important to avoid an infinite loop of willSaves.)

    This postpones the deletion of the orphaned catalogs or products until save time. This is probably not a problem.

    0 讨论(0)
  • 2021-02-12 12:04

    Swift translation of Andy and JosephH

    override func willSave() {
        super.willSave()
    
        if self.deleted {
          return
        }
    
        if self.products.count == 0 {
          self.managedObjectContext?.deleteObject(self)
        }
      }
    
    0 讨论(0)
  • 2021-02-12 12:06

    I've implemented rgeorge's answer, and thought the exact code might be helpful to other people:

    - (void)willSave
    {
        [super willSave];
    
        if (self.isDeleted)
            return;
    
        if (self.products.count == 0)
            [self.managedObjectContext deleteObject:self];
    }
    
    0 讨论(0)
提交回复
热议问题