Typeorm BaseEntity创建函数:如何深度创建实体?

时间:2019-11-24 14:39:12

标签: typeorm

我有一个Patient实体:

@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 create函数创建患者实例时,会创建患者,但在医疗条件数组中仅包含最后一个元素,即使有很多元素,其余所有元素也会消失。

@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: '' } ],

尝试过google,未发现任何已知问题。

所以愿意的结果是深入创建实体,这是可能的行为吗?

0 个答案:

没有答案