所以我有一个带有Deck表,Card表和DeckCard表的数据库,因为这两者之间存在多对多的关系...当我尝试删除卡片组时,我删除了ID匹配的DeckCard行并且我已经将外键设置为onDelete = CASCADE,但是它没有删除任何提示吗?这是我n对n区别的存储库
public class DeckCardRepository {
private DeckWithCardsDao mDeckWithCardsDao;
public void delete(Deck deck){
DecksDatabase.databaseWriteExecutor.execute(() ->
mDeckWithCardsDao.delete(deck.getId()));
}
}
甲板类
@Entity(tableName = "decks")
public class Deck implements Serializable {
@PrimaryKey
private long id;
private String keyforgeId;
private String name;
@TypeConverters({ExpansionTypeConverter.class})
private Expansion expansion;
private int creatureCount;
private int actionCount;
private int artifactCount;
private int upgradeCount;
private int sasRating;
private int powerLevel;
private int chains;
private int wins;
private int losses;
private int totalPower;
private int totalArmor;
private int localWins;
private int localLosses;
}
卡类
Entity(tableName = "cards")
public class Card implements Serializable {
@PrimaryKey
@NonNull
private String id;
private String card_title;
private String card_type;
@TypeConverters({HouseArrayTypeConverter.class})
private House house;
private String card_text;
private int amber;
private String front_image;
}
卡组等级
Entity(tableName = "cards_deck_join",
primaryKeys = {"cardId", "deckId"},
foreignKeys = {
@ForeignKey(
entity = Card.class,
parentColumns = "id",
childColumns = "cardId"),
@ForeignKey(onDelete = CASCADE,
entity = Deck.class,
parentColumns = "id",
childColumns = "deckId"),
})
public class CardsDeckRef {
@NonNull
private String cardId;
private long deckId;
private int count;
public CardsDeckRef(String cardId, long deckId, int count) {
this.cardId = cardId;
this.deckId = deckId;
this.count = count;
}
}
MyDao
@Dao
public interface DeckWithCardsDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void add(CardsDeckRef cardsDeckRef);
@Transaction
@Query("SELECT * FROM cards INNER JOIN cards_deck_join" +
" ON cards.id=cards_deck_join.cardId WHERE cards_deck_join.deckId =:deckId")
LiveData<List<Card>> getCardsForDeck(final long deckId);
@Query("DELETE FROM cards_deck_join WHERE cards_deck_join.deckId=:deckId ")
void delete(final long deckId);
}
ON CASCADE DELETEonDelete = CASCADE如果删除了父级,则(即添加到表中的内容)将删除子级。如果有孩子,甚至所有孩子都被删除,它也不会删除父母。
而不是删除一个牌组以及与该牌组相关联的所有card_deck_join行
@Query("DELETE FROM decks WHERE id=:deckId ")
void delete(final long deckId);
然后,删除卡片组将被向下层叠到cards_deck_join表中。
如果要自动删除卡组,如果从cards_deck_join中删除后没有子组,则可以使用TRIGGER例如
CREATE TRIGGER IF NOT EXISTS delete_empty_deck
AFTER DELETE ON card_deck_join
BEGIN
DELETE FROM decks
WHERE (SELECT count(*) FROM card_deck_join WHERE deckid = old.deckid) = 0 AND decks.id = old.deckid;
END;
由于会议室不支持生成触发器(据我所知,除了FTS确实会生成某些触发器时),您必须在会议室外部添加TRIGGER(例如,通过覆盖onCreate或callBack的callBack) OnOpen)。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。