【问题标题】:ActiveAndroid One-To-Many relationship with CascadeActiveAndroid 与 Cascade 的一对多关系
【发布时间】:2019-07-07 06:33:07
【问题描述】:

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

    @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&lt;CheckList&gt; Checklists; 中与此Equipment 相关的所有记录也删除。我知道我可以进行查询等,但我需要知道是否有更好的方法和正确的方法来做到这一点?

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

【问题讨论】:

    标签: android activeandroid


    【解决方案1】:

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

    @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. Reference article
    2. Possible values for ForeignKeyAction
    3. Official docs with basics on how to set up relationships & models
    4. Closed issue that confirms that CASCADE DELETE works

    【讨论】:

    • 我需要更多解释。我也不明白你的例子。我不需要与title 有任何关系。您能否详细解释一下(如何稍后创建关系和查询)并展示与我的问题相关的示例?
    • 我只是以title 列为例。您基本上需要在Checklist 表中保留一个与Equipment 表中的主键相关联的外键。这样,当Equipment 中的一行被删除时,它会级联到Checklist 表。
    • 你的回答没有帮助。我不能只复制onDelete = ForeignKeyAction.CASCADE 并将其放在我想要的任何地方吗?我需要知道这是如何工作的。如果是这样的话,我会自己做的。问题是我不知道级联如何与项目列表一起工作,它们会被删除吗?我怎样才能将该列表查询到相关项目。
    • @lvl4fi4 检查我在答案中添加的参考链接。我目前无法访问我的笔记本电脑,我会尽量添加完整的代码。
    • 好吧,我想我错过了答案中的一个关键点,我的错。您基本上不会创建项目列表,而是创建一个返回项目列表的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2018-03-16
    • 2011-11-09
    • 2012-06-14
    • 2011-06-22
    • 2018-11-02
    相关资源
    最近更新 更多