问题描述
我目前在运行时从数据库中删除实体列表时遇到问题:
const cards = Card.find(...);
await Card.remove(cards);
某些卡未移除,并且我的卡座未更新为正确的长度。但是,当我运行时:
const cards = Card.find(...);
for (const card of cards) {
await Card.remove(card);
}
它可以正确删除元素,因此我认为它与Card.remove(...)
如何异步删除实体有关。
我的数据库架构中有以下双重链接列表部分,用于一副纸牌。
decks
id (PK)
head_card_id (FK)
tail_card_id (FK)
length
cards
id (PK)
deck_id (FK)
next_card_id (FK)
prev_card_id (FK)
我正在使用TypeORM定义我的实体。这是我的Card实体的定义:
@Entity('cards')
export class Card extends BaseEntity {
@PrimaryColumn()
id: string;
@ManyToOne(() => Deck,(deck) => deck.cards,{ onDelete: 'CASCADE' })
deck: Deck;
@Column()
deckId: string;
@ManyToOne(() => Card,(card) => card.prevCard,{
nullable: true,cascade: false,onDelete: 'SET NULL',})
nextCard: Card;
@Column({ nullable: true,default: null })
nextCardId?: string;
@ManyToOne(() => Card,(card) => card.nextCard,})
prevCard: Card;
@Column({ nullable: true,default: null })
prevCardId?: string;
@BeforeInsert()
addId(): void {
this.id = v4();
}
@BeforeRemove()
async safeRemove(): Promise<void> {
const deck = await Deck.findOneOrFail({
where: { id: this.deckId },});
const nextCard = await Card.findOne({
where: { id: this.nextCardId },});
const prevCard = await Card.findOne({
where: { id: this.prevCardId },});
// Card is headCard and tailCard (only card)
if (deck.headCardId === this.id && deck.tailCardId === this.id) {
await Deck.update(this.deckId,{
headCardId: prevCard?.id,tailCardId: nextCard?.id,length: deck.length - 1,});
}
// Card is headCard in Deck
else if (deck.headCardId === this.id) {
await Deck.update(this.deckId,});
}
// Card is tailCard in Deck
else if (deck.tailCardId === this.id) {
await Deck.update(this.deckId,{
tailCardId: nextCard?.id,});
}
// Card is not headCard or tailCard
else {
await Deck.update(this.decktId,{
length: deck.length - 1,});
}
// Card has nextCard
if (nextCard?.id) {
await Card.update(nextCard.id,{
prevCardId: prevCard?.id,});
}
// Card has prevCard
if (prevCard?.id) {
await Card.update(prevCard.id,{
nextCardId: nextCard?.id,});
}
}
}
我做错了什么吗,还是有一种方法可以编写我的@BeforeRemove方法以使其正常工作?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)