gpt4 book ai didi

foreign-keys - TypeORM:如何显式设置ForeignKey而没有用于加载关系的属性?

转载 作者:行者123 更新时间:2023-12-04 15:38:51 29 4
gpt4 key购买 nike

我不想创建用于将关系加载到其中的属性(如所有示例所示)。我唯一需要做的就是拥有一个明确的外键属性,以便迁移能够在数据库中为其创建适当的约束。与我需要的装饰器最接近的装饰器是@RelationId,但它仍然需要存在关系类的属性。

为了清楚起见,让我们以文档中的示例为例:

@Entity()
export class Post {
@ManyToOne(type => Category)
category: Category;

@RelationId((post: Post) => post.category) // it still requires the presence of the `category` proeprty
categoryId: number;

}

我在这里不需要 category属性。我想拥有 categoryId属性,并将其标记为 Category.Id的外键。它看起来应该像这样:
@Entity()
export class Post {

@ForeignKey((category: Category) => category.Id) // it's a foreign key to Category.Id
categoryId: number;

}

是否可以?

最佳答案

也许您可以创建和编写自己的迁移并像这样使用它:

    const queryRunner = connection.createQueryRunner();
await queryRunner.createTable(new Table({
name: "question",
columns: [
{
name: "id",
type: "int",
isPrimary: true
},
{
name: "name",
type: "varchar",
}
]
}), true);

await queryRunner.createTable(new Table({
name: "answer",
columns: [
{
name: "id",
type: "int",
isPrimary: true
},
{
name: "name",
type: "varchar",
},
{
name: "questionId",
isUnique: connection.driver instanceof CockroachDriver, // CockroachDB requires UNIQUE constraints on referenced columns
type: "int",
}
]
}), true);

// clear sqls in memory to avoid removing tables when down queries executed.
queryRunner.clearSqlMemory();

const foreignKey = new TableForeignKey({
columnNames: ["questionId"],
referencedColumnNames: ["id"],
referencedTableName: "question",
onDelete: "CASCADE"
});
await queryRunner.createForeignKey("answer", foreignKey);

该代码段是从orm类型的 functional test中提取的,您可以使用它在我认为的数据库上创建自己的约束。

关于foreign-keys - TypeORM:如何显式设置ForeignKey而没有用于加载关系的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170906/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com