首页 > 解决方案 > ActiveAndroid 与 Cascade 的一对多关系

问题描述

我对如何创建两个与条件相关的表Model有点困惑,并且找不到任何好的/清晰的例子来学习。所以我有这张桌子:ActiveAndroidCascadeonDelete

    @Table(name = "CheckList")
    public class CheckList {

    @Column(name = "Title")
    String Title;
    @Column(name = "After")
    Integer After;
    @Column(name = "Before")
    Integer Before;

    @Column(name = "Enabled")
    Boolean Enabled;

    @Column(name = "Info")
    String Info;
}

我需要在此表中列出它:

@Table(name = "Equipment")
public class Equipment {

    @Column(name = "Title")
    String Title;

    @Column(name = "Checklists")
    List<CheckList> Checklists;

}

我也可能有另一个表,其中包含列表,Equipment我需要像上面一样将它们关联起来。

我想要的是,当我从中删除记录时Equipment,我需要删除List<CheckList> Checklists;与此相关的所有记录Equipment。我知道我可以进行查询等,但我需要知道是否有更好的方法和正确的方法来做到这一点?

请详细解释(如何稍后创建关系和查询)并显示与我的表相关的示例。

标签: androidactiveandroid

解决方案


您需要设置具有外键级联关系的表。

@Table(name = "Equipment")
public class Equipment {

    @Column(name = "Title")
    String Title;

    // This method is optional & does not affect the foreign key creation.
    public List<CheckList> items() {
        return getMany(CheckList.class, "Equipment");
    }
}

@Table(name = "CheckList")
public class CheckList {

    @Column(name = "Title")
    String Title;

    @Column(name = "After")
    Integer After;

    @Column(name = "Before")
    Integer Before;

    @Column(name = "Enabled")
    Boolean Enabled;

    @Column(name = "Info")
    String Info;

    //This establishes a relationship between Checklist and Equipment, Any update or delete operations done on Equipment table gets cascaded to the corresponding rows in the Checklist table.
    @Column(name = "Equipment", onUpdate = ForeignKeyAction.CASCADE, onDelete = ForeignKeyAction.CASCADE)
    Equipment equipment;

}

参考资料:

  1. 参考文章
  2. ForeignKeyAction 的可能值
  3. 官方文档,其中包含有关如何建立关系和模型的基础知识
  4. 确认 CASCADE DELETE 有效的已关闭问题

推荐阅读