微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决TypeORM为什么我的关系列未定义?外键未定义

我只是使用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
}

数据库表如下:

"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,如何输入ORM?外键是否存在未定义?

解决方法

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

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,{ nullable: true})
    belong_organization!: Organization;
    ...
}

这也可以查询其ID。

您也可以直接查询它,但这会给您留下一些非常难看且难以维护的代码:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。