与Cascade的ActiveAndroid一对多关系

时间:2019-07-07 06:33:07

标签: android activeandroid

我对如何使用Model创建ActiveAndroid并使其具有两个与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<CheckList> Checklists;中与此Equipment相关的所有记录。我知道我可以进行查询等等,但是我需要知道是否有更好的方法和正确的方法来做到这一点?

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

1 个答案:

答案 0 :(得分:0)

您需要使用外键级联关系设置表。

@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