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

2024-04-14

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

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

当我使用Repository like:

 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,typeORM 如何做到这一点?外键存在未定义?


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

Lazy https://typeorm.io/#/eager-and-lazy-relations/lazy-relations:

@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 https://typeorm.io/#/find-options

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
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • 如何将连接用作具有类型的独立对象?

    不工作的代码只是为了说明我想要实现的目标 一些连接文件 import ConnectionManager from typeorm const c new ConnectionManager user ormconfig conf file
  • 单个表的多个外键和指向多个表的单个键

    我需要数据库设计专家的一些建议 我在一个表中有大约六个外键 缺陷 它们都指向用户表中的主键 它像是 defect assigned to created by updated by closed by 如果我想获取有关缺陷的信息 我可以进行
  • 如何首先在 Entity Framework 5 代码中使用两个外键创建主键?

    我有一个实体 其中主键由另外两个表的两个外键组成 我的配置使用以下内容 但该表是使用两个 FK 引用生成的 桌子 domain Entity1 MorePK PK FK int not null Entity2 Id PK FK int n
  • 引用 Oracle 中视图的外键

    我尝试使用外键引用视图 但收到此错误 错误 ORA 02270 此列列表没有匹配的唯一键或主键 不过 我已在此视图上创建了一个主键 并在 TOAD 的 约束 选项卡中对其进行了验证 这是我试图创建的表 CREATE TABLE QUESTI
  • 如何使用 Jest 单元测试覆盖 TypeORM @Column 装饰器?

    我希望尽可能多地对我的应用程序进行单元和端到端测试 我的目标是覆盖率达到 101 我的设置现在的问题是 typeorm 的 Column 装饰器使用箭头函数来设置默认值 例如数据库更新的当前时间戳 这个箭头函数没有被玩笑测试覆盖 消息是 s
  • NestJS,如何以及在哪里构建响应 DTO

    我一直在使用Java Spring框架来开发微服务 最近 我开始探索 NestJS 并有一个关于构建响应 DTO 的问题 在春天 控制器是轻量级的 它们将调用交给服务层 服务层实现业务逻辑 最后 它们调用负责构建响应 DTO 的 Mappe
  • 为什么外键在 websql 中不起作用..?

    我尝试使用 web sql 在我的应用程序中使用外键 我在 chrome 中测试它 没有错误 但是当我测试手动插入表 img 包含 FK 我预计会失败 但插入仍然成功 这是我的代码 请帮助我 tx executeSql PRAGMA for
  • 如果父级未被任何其他子级引用,则删除父级

    我有一个示例情况 parent表有一列名为id 引用于child表作为外键 删除子行时 如果父行未被任何其他子行引用 如何同时删除父行 在 PostgreSQL 中9 1 或更高版本您可以使用单个语句来完成此操作数据修改CTE https
  • MySQL 8.x 中的主要错误? -- 外键

    当从 MySQL 用于代码生成器 检索外键信息时 我注意到这种奇怪的行为 它看起来像是 MySQL 8 x 中的一个主要错误 当我使用创建外键时REFERENCES引擎不强制执行它 例如 create table p id int prim
  • django:预取 GenericForeignKey 的相关对象

    假设我有一个模型Box with a GenericForeignKey指向任一Apple实例或Chocolate实例 Apple and Chocolate 反过来 有外键Farm and Factory 分别 我想显示一个列表Boxes
  • 如何将外键字段添加到 Django 中的 ModelForm?

    我想做的是显示一个表单 让用户 输入文档标题 来自Document model 选择他们的其中之一user defined code从下拉列表中进行选择 由UserDefinedCode model 输入一个unique code 存储在C
  • 使用 Entity Framework 7 的 Fluent-API 创建可选外键

    我正在尝试使用 Entity Framework 7 和 Fluent API 创建可选外键 在 EF v6 x 中 我们可以选择使用以下命令添加此内容 WithOptional or HasOptional 但我在 EF 7 中找不到任何
  • 没有子导航属性的 EF 一对多外键

    使用代码优先的实体框架和 NET 4 我尝试在父母与孩子之间创建一对多关系 public class Parent Key public int ParentId get set Required public string ParentN
  • Hibernate 单向一对多关联 - 为什么连接表更好?

    在本文档中 向下滚动到单向部分 http docs jboss org hibernate stable annotations reference en html single entity mapping association col
  • Hibernate 复合键:外键的列数错误

    我是 Hibernate 和 JPA 的新手 在设置复合键时遇到困难 定义如下 Entity Table name Entity TABLE IdClass EntityPK class public class MyEntity exte
  • MVC 中的外键注释

    我有两张桌子 State StateID int StateName string City CityID int StateID int CityName string 我正在使用代码优先方法开发 MVC4 代码 我正在使用State a
  • 事件源和 SQL Server 多个关系表

    我们使用 SQL Server 2016 的事件源 我们有完整的客户产品应用程序 每个应用程序都标记为CustomerId并在事件商店中获取单个指南行项目 这是写入事件存储指南的主要标识符 产品应用程序附带许多不同的关系事物 没有引导 但有
  • 如何从其他表填充表的外键

    我有以下表格 其中translation是空的 我正在尝试填充 translation id translated language id template id language id langname langcode template
  • 如何在 typeorm 中使用 LEFT JOIN LATERAL?

    我想在 TypeOrm 中使用以下查询 但找不到将其转换为 TypeOrm 的方法 任何帮助表示赞赏 SELECT FROM blocked times bt LEFT JOIN LATERAL SELECT FROM bookings b
  • 设置约束可延迟在 PostgreSQL 事务上不起作用

    情况是这样的 我有两个表 其中一个引用另一个 例如 table2 引用 table1 创建这些表时 我确实将外键约束设置为 DEFERRABLE 将 ON UPDATE 和 ON DELETE 子句设置为 NO ACTION 这是默认值 但

随机推荐