typeorm - Typeorm BaseEntity 创建函数:如何深度创建实体?
问题描述
我有一个患者实体:
@Entity()
@ObjectType()
@InputType('PatientInput')
export class Patient extends BaseEntity {
@PrimaryGeneratedColumn()
@Field(type => Int, { nullable: true })
id: number
@Column({ length: 500 })
@Field({ nullable: true })
firstName?: string
@Column({ length: 500 })
@Field({ nullable: true })
lastName?: string
@Field(type => MedicalCondition, { nullable: true })
@OneToMany(type => MedicalCondition, medicalCondition => medicalCondition.patient, { cascade: true })
medicalConditions?: MedicalCondition[]
}
还有一个 MedicalCondition 实体:
@ObjectType()
@Entity()
@InputType('medicalCondition')
export class MedicalCondition extends BaseEntity {
@Field({nullable: true})
@PrimaryGeneratedColumn()
id: number
@Field(type => Int, { nullable: true })
@RelationId((medicalCondition: MedicalCondition) => medicalCondition.patient)
@Column()
patientId?: number
@Field(type => Patient, { nullable: true })
@ManyToOne(type => Patient, patient => patient.medicalConditions, {
onDelete: 'CASCADE',
})
@JoinColumn()
patient?: Patient
@Field()
@Column()
name: string
@Field({nullable: true})
@Column()
startDate?: Date
}
当尝试使用 BaseEntity 创建函数创建患者实例时,会创建患者,但在医疗条件数组中仅包含最后一个元素,即使有很多元素,其余元素也会消失。
@Mutation(returns => Patient)
async create(@Args('patient') newPatientInput: Patient, @CurrentUser() user: User, @Useragent() useragent): Promise<Patient> {
const newPatient: Patient = Patient.create(newPatientInput)
const event = createEvent({ useragent, actionType: 'add_patient', userId: user.id })
const p = await this.patientService.create(newPatient, event)
return p
}
create = async (patient: Patient, event: EventLog): Promise<Patient> => {
const isExist = await this.isPatientExist({ firstName: patient.firstName, lastName: patient.lastName, birthDate: patient.birthDate })
if (isExist > 0) {
throw new Error('Patient already exist')
} else {
const transactionResult = runTransaction(async (em) => {
const eventLog = EventLog.create(event)
await em.save(eventLog)
return await em.save(patient)
})
return transactionResult
}
}
我试图直接保存实体而不调用create()
:
return await em.save(Patient, patient)
这就是保存的结果:
medicalConditions:
[ { id: 36,
name: 'heartDisease',
startDate: 2016-07-31T21:00:00.000Z,
kin: 'father',
note: '',
patientId: 26,
createdAt: 2019-11-24T17:11:22.376Z,
updatedAt: 2019-11-24T17:11:22.376Z },
{ id: null,
name: 'previousHeartAttack',
startDate: 2018-04-30T21:00:00.000Z,
kin: 'brother',
note: '' },
{ id: null,
name: 'highBloodPressure',
startDate: 2018-03-31T21:00:00.000Z,
kin: 'sister',
note: '' } ],
尝试谷歌并没有发现任何已知问题。
所以愿意的结果是深度创建一个实体,这是一种可能的行为吗?
解决方案
推荐阅读
- c# - 使用 LINQ 的 EF 动态字段选择
- c# - 访问 List 的字段
通过字符串 - java - 您如何将三个十个 Backport 类与 JDBC 一起使用?
- python - 在 pytz 中提取时区偏移的更优雅的方法是什么?
- javascript - 使用 forEach 比较先前的值
- vbscript - 从 Asp 经典页面访问 .NET TimezoneInfo 的最简单方法
- webpack - Webpack URLLoader 限制要小
- python - 如果 __init__ 包含 Clock.schedule_interval,Kivy 崩溃
- bash - Shell 脚本数组未打印正确的值
- python - 在字典中查找最高值