【问题标题】:TypeORM can find() with relationsTypeORM 可以 find() 与关系
【发布时间】:2020-06-23 17:23:13
【问题描述】:

我是第一次使用 TypeORM,不幸的是不得不使用 JavaScript。文档主要关注 TypeScript,所以我在尝试获取包含所有相关其他条目的条目时遇到了困难。

module.exports = {
    name: "recordings",
    columns: {
        id: {
            type: "uuid",
            primary: true,
            generated: "uuid"
        },
        title: {
            type: "text",
            unique: true,
            nullable: false
        },
        file: {
            type: "text",
            unique: true,
            nullable: false
        }
    },
    relations: {
        recordingAnnotations: {
            target: "recordingAnnotations",
            type: "one-to-many",
            joinTable: true,
        }
    }
};

module.exports = {
    name: "recordingAnnotations",
    columns: {
        id: {
            type: "uuid",
            primary: true,
            generated: "uuid"
        },
        startsAt: {
            type: "int",
            nullable: false
        },
        endsAt: {
            type: "int",
            nullable: false
        },
        content: {
            type: "text",
            unique: true,
            nullable: false
        }
    },
    relations: {
        recording: {
            target: "recordings",
            type: "many-to-one",
            nullable: false,
            onDelete: "CASCADE"
        }
    }
};

现在我想找到一个包含所有注释的recording 条目。

const repo = conn.getRepository(Recording.name);
const result = await repo.find({
    where: { id },
    relations: [ "recordingAnnotations" ]
});

我想要得到的结果如下所示:

    id: "some-uuid",
    title: "Recording 1",
    file: "some-uuid",
    annotations: [
        { id: "some-uuid", startsAt: 0, endsAt: 10, content: "Hello!" },
        { id: "some-uuid", startsAt: 20, endsAt: 25, content: "Bye!" },
    ]

我得到的错误:

TypeError: 无法读取未定义的属性'joinColumns'

【问题讨论】:

    标签: javascript node.js postgresql orm typeorm


    【解决方案1】:

    在录制模式中,不需要joinTable,因为它只适用于多对多关系,

    relations: {
        recordingAnnotations: {
            target: "recordingAnnotations",
            type: "one-to-many",
            inverseSide: 'recording'
        }
    }
    

    我们需要将inverseSide指定为recording,因为我们在recordingAnnotations架构中添加了recording关系,并且ManyToOne将外键放在当前实体表中。

    在recordingAnnotations架构中,

    relations: {
        recording: {
            target: "recordings",
            type: "many-to-one",
            nullable: false,
            onDelete: "CASCADE",
            joinColumn: true
        }
    }
    

    我们需要指定joinColumn,它将在recordingAnnotations表中添加recordingId(Foreign Key)。

    另外,这里是使用一对多关系的完整示例:https://github.com/typeorm/typeorm/issues/2503#issuecomment-404834720

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 2021-12-27
      • 2021-06-10
      • 2021-12-23
      • 2020-08-09
      • 2021-01-17
      • 2018-08-03
      • 2020-04-06
      相关资源
      最近更新 更多