TypeORM 为什么我的关系列未定义?外键未定义

TypeORM why is my relationship column undefined? foreign-key is undefined

我刚刚使用 TypeORM,发现关系列未定义


@Entity({name: 'person'})
export class Person {
    @PrimaryGeneratedColumn('uuid')
    id!: string;

    @OneToOne( () => User)
    @JoinColumn()
    user!: User;

    @Column({
        type: "enum",
        enum: PersonTitle,
        default: PersonTitle.Blank
        })
    title?: string;

    @Column({type: 'varchar', default: ''})
    first_name!: string;

    @Column('varchar')
    last_name!: string;

    @ManyToOne(() => Organization, org => org.people, { nullable: true})
    belong_organization!: Organization;

而且我还有 Organization 个实体:

export class Organization {
    @PrimaryGeneratedColumn('uuid')
    id!: string;
...
}

当我使用 Repository 时:

 const db = await getDatabaseConnection()
 const prep = db.getRepository<Person>('person')
 presult = await prep.findOne({where: {id}})
 console.log(result)

我的结果是:

Person {
  id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
  user: undefined,
  title: 'Mr.',
  first_name: 'ss',
  last_name: 'ls',
  belong_organization: undefined,  // I just want to know why is undefined? even I can find in database the column
  expertise: [],
  introduction: 'input introduction',
  COVID_19: false,
  contact: undefined
}

数据库table喜欢:

"id"    "title" "first_name"    "last_name" "expertise" "COVID_19"  "userId"    "belongOrganizationId"  "introduction"
"75c37eb9-1d88-4d0c-a927-1f9e3d909aef"  "Mr."   "test"  "tester"    "nothing"   "0" "be426167-f471-4092-80dc-7aef67f13bac"  "8fc50c9e-b598-483e-a00b-1d401c1b3d61"  "input introduction"

我想显示组织id,typeORM怎么办?外键存在未定义?

您需要延迟加载关系或需要在查找中指定关系

Lazy:

@Entity({name: 'person'})
class Person {
    ...
    @ManyToOne(() => Organization, org => org.people, { nullable: true})
    belong_organization!: Organization;
    ...
}

...

async logOrganization() {
    const db = await getDatabaseConnection()
    const prep = db.getRepository<Person>('person')
    presult = await prep.findOne({where: {id}})
    console.log(await result.belong_organization)
}

Find

const prep = db.getRepository<Person>('person')
presult = await prep.findOne({
    where: { id },
    relations: ["belong_organization"]
})

您也可以始终执行预加载,但我建议您不要这样做,因为它会在获取人员时始终执行连接。

如果你想查询belong_organizationId你需要将它的字段添加到person实体。该字段通常类似于 belongOrganizationId

那会使

@Entity({name: 'person'})
class Person {
    ...
    @Column()
    belongOrganizationId:number

    @ManyToOne(() => Organization, org => org.people, { nullable: true})
    belong_organization!: Organization;
    ...
}

这样也可以查询其 ID。

您也可以更直接地查询它,但这会给您留下一些非常丑陋且无法维护的代码:

const findOptions: {
    where :{
        id,
        'belong_organization.id': belong_organizationId
    }
}