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.
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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With