androidactiveandroid

ActiveAndroid One-To-Many relationship with Cascade


I'm little bit confused about how to create Model with ActiveAndroid to have two tables related with Cascade condition onDelete and coudn't find any good/clear example to learn from. so i have this table :

    @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;
}

and i need to have list of it in this table :

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

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

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

}

also i may have another table with list of Equipment in it and i need to relate them just like above.

what i want is that when i delete a record from Equipment and i need to all record in List<CheckList> Checklists; that related to this Equipment to be deleted as well. i know i can do a query and so on but i need to know is there a better way and right way to do this?

Please explain with details (how to create relation and query later ) and show an example related to my tables.


Solution

  • You'll need to set up the tables with a foreign key cascade relationship.

    @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;
    
    }
    

    Reference materials:

    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