如何解决Mikro-orm 在集合上调用 remove() 会删除所有内容,而不仅仅是一个
我目前正在实现用户和产品之间的 M:M 关系,该关系使用自定义联接表来实现购物车。这是自定义连接表:
@Entity({ tableName: "users_in_cart_products" })
export class UserInCartProducts {
@ManyToOne(() => User,{ primary: true,nullable: true })
user: User;
@ManyToOne(() => Product,nullable: true })
product: Product;
@property()
amount: number;
}
用户实体的组成部分(类似于产品)
@Entity({ tableName: "users",customrepository: () => UserRepository })
export class User {
@PrimaryKey()
id: string = v4();
/* some properties */
@OnetoMany(() => UserInCartProducts,(userInCartProducts) => userInCartProducts.user)
userInCartProducts = new Collection<UserInCartProducts>(this);
}
我目前正在实施一项功能,可将产品从购物车中删除。但是,当我调用 user.userInCartProducts.remove() 时,它不仅会删除该元素,还会删除 user.userInCartProducts 中的所有内容,并留下一个空数组。这是从用户的购物车中删除产品的代码:
async removeCartItem(userId: string,productId: string) {
const user = await this.userRepository.findOneOrFail({ id: userId },[
"userInCartProducts","userInCartProducts.product",]);
for (const e of user.userInCartProducts) {
if (e.product.id === productId) user.userInCartProducts.remove(e);
}
await this.userRepository.persistAndFlush(user);
return user;
}
我检查了从 Mikro-orm 生成的 sql,并以某种方式将 users_in_cart_products 连接表中的所有内容的 user_id 设置为 NULL:
[query] update "users_in_cart_products" set "user_id" = NULL [took 2808 ms]
那么我该如何解决这个问题呢?我只希望该集合删除该项目,但不是每个项目。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。