一对一的typeform级联删除



我阅读和搜索了很多,但没有找到任何解决我的问题的方法。我读了这个,这个,…

我的数据库是MySQL。一对多和多对多都没有问题。在一对一关系中
// Student.ts(Parent)
@Entity({ name: "student" })
export class StudentEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column({ nullable: true })
public name: string;
@OneToOne(() => StudentProfile, (profile) => profile.student, { onDelete: "CASCADE", cascade: ['insert', 'update'] })
public profile: StudentProfile
}

// Profile.ts
@Entity({ name: "profile" })
export class StudentProfile {
@PrimaryGeneratedColumn()
id: number
@Column({ nullable: true })
username: string
@OneToOne(() => StudentEntity, (student) => student.profile, { onDelete: "CASCADE" })
public student: StudentEntity
}

现在,使用以下代码,我想删除学生和他们的配置文件:

const student = await this._studentRepository.findOne({ where: { id: 4 } })
await this._studentRepository.delete(student)

上面的代码不起作用。还有另一种方法:我可以单独删除学生和个人资料,我不想这样做。

任何帮助将不胜感激。提前谢谢。

正如你所包含的stackoverflow所提到的:你必须删除引用方才能使级联删除生效。

我猜你得这样删除:

const student = await this._studentRepository.findOne({ where: { id: 4 } })
const profile = await this._profileRepository.findOne({ where: { id: student.profile } }) // if you don't have an eager relationship
await this._profileRepository.delete(profile)

或者如果student和profile之间存在渴望关系:

const student = await this._studentRepository.findOne({ where: { id: 4 } })
await this._profileRepository.delete(student.profile) // if you've an eager relationship

最新更新