Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room On delete Cascade doesn't work

I know there are a lot of posts about this kind of subject but they all deal with SQLite... (mine is about Room).

I have a one-to-many relation between a "Card" table and a "Deck" table. So a card has 1 Deck and a Deck has Many cards. Insertion and Deletion are OK for 1 row but i'd like to delete the cards of a deck when this one is removed : on Delete cascade relationship.

My code :

(Card.class)

@Entity(tableName = "cards")
public class Card{

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public int id;

    @ColumnInfo(name = "face1")
    public String face1;

    @ColumnInfo(name = "face2")
    public String face2;

    @ColumnInfo(name = "id_deck")
    @ForeignKey(entity = Deck.class, parentColumns = "id", childColumns = 
    "id_deck", onDelete = CASCADE)
    public int id_deck;
}

Deck.class :

@Entity(tableName = "decks")
public class Deck {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public int id;

    @ColumnInfo(name = "nom")
    public String nom;

    public Deck(String nom){
        this.nom = nom;
    }

}

Did i make something wrong ? When I remove a Deck, the cards still exist.

like image 751
R. SAM Avatar asked Jan 01 '23 12:01

R. SAM


1 Answers

You should define your foreign keys inside your @Entity annotation.

@Entity(tableName = "cards", foreignKeys = @ForeignKey(entity = Deck.class, parentColumns = "id", childColumns = "id_deck", onDelete = CASCADE))

Update for Kotlin

@Entity(tableName = "cards", foreignKeys = [ForeignKey(entity = Deck::class, parentColumns = ["id"], childColumns = ["id_deck"], onDelete = ForeignKey.CASCADE)])
like image 189
musooff Avatar answered Jan 10 '23 08:01

musooff