gpt4 book ai didi

mysql - 如何使用 onDelete : 'CASCADE' on one-to-one relationship

转载 作者:行者123 更新时间:2023-12-05 01:34:08 25 4
gpt4 key购买 nike

当用户被删除时,我尝试删除用户的个人资料。但它不会删除个人资料上的任何内容。

用户实体

@Entity()
export class User {

@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@OneToOne(type => Profile, profile => profile.user,
{ eager: true, cascade: true, onDelete: 'CASCADE' })
@JoinColumn()
profile: Profile;

}

个人资料实体

@Entity()
export class Profile {

@PrimaryGeneratedColumn()
id: number;

@Column()
gender: string;

@Column()
photo: string;

@OneToOne(type => User, user => user.profile)
user: User;

}

我如何删除用户。

const userRepository = connection.getRepository(User);
const user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: ["profile"] });

await user.remove()

用户已被删除,但用户的个人资料没有任何变化。

Can anyone explain how to delete relationship on one-to-one?

最佳答案

用户

@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@OneToOne(type => Profile, profile => profile.user,
{ eager: true, onDelete: 'CASCADE' })
@JoinColumn()
profile: Profile;
}

简介

@Entity()
export class Profile {

@PrimaryGeneratedColumn()
id: number;

@Column()
gender: string;

@Column()
photo: string;

@OneToOne(type => User, user => user.profile, { onDelete: "CASCADE" })
user: User;

}

我运行了这段代码以从两个实体中删除条目。

const userRepository = connection.getRepository(User);
const user = await userRepository.findOne({ where: {id: 'someuserId'} });

const profileRepository = connection.getRepository(Profile);
const profile = await profileRepository.findOne({ where: {id: user.profile.id} });

await profileRepository.remove(profile)

这是一对一关系的预期行为。 必须删除引用端才能使级联删除生效。讨论link

编辑:github 上提出问题

关于mysql - 如何使用 onDelete : 'CASCADE' on one-to-one relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64002621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com