Android Room On delete Cascade 不起作用

Android Room On delete Cascade doesn't work

我知道有很多关于此类主题的帖子,但它们都涉及 SQLite...(我的帖子是关于 Room 的)。

我在 "Card" table 和 "Deck" table 之间存在一对多关系。所以一张卡片有 1 张牌,一张牌有很多牌。插入和删除对于 1 行是可以的,但我想在删除这个卡片时删除卡片组中的卡片:关于删除级联关系。

我的代码:

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

}

我是不是做错了什么?当我移除牌组时,牌仍然存在。

您应该在 @Entity 注释中定义外键。

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

Kotlin 更新

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