繁体   English   中英

TypeORM 可以 find() 与关系

[英]TypeORM can find() with relations

我第一次使用 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!" },
    ]

我得到的错误:

类型错误:无法读取未定义的属性'joinColumns'

在记录模式中,无需 joinTable,因为它只能处理多对多关系,

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

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

在记录注释模式中,

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM