【发布时间】:2019-06-14 07:19:33
【问题描述】:
我有一个使用 TypeORM 和 PostgreSQL 数据库的 Typescript Nestjs 项目,但我无法定义多对一关系,因为 TypeORM 尝试创建整数类型的 ID 字段,而我使用的是 UUID 字段。有没有办法告诉 TypeORM 使用与整数不同的数据类型?
这是一个不工作的实体示例:
export class AgentKitsEntity implements Model {
@PrimaryGeneratedColumn()
@Generated('uuid')
id: string;
}
@Entity({name: 'users'})
export class User extends AgentKitsEntity implements UserModel {
@Column()
username: string;
@ManyToOne(type => View)
@JoinColumn({name: 'view_id', referencedColumnName: 'id'})
view: View;
}
这会导致以下错误:
query failed: ALTER TABLE "users" ADD CONSTRAINT "FK_2ed8b186dce83a446f94ac9aae4" FOREIGN KEY ("view_id") REFERENCES "views"("id")
error: { error: foreign key constraint "FK_2ed8b186dce83a446f94ac9aae4" cannot be implemented
at Connection.parseE (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:554:11)
at Connection.parseMessage (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:379:19)
at Socket.<anonymous> (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:119:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:601:20)
name: 'error',
length: 228,
severity: 'ERROR',
code: '42804',
detail: 'Key columns "view_id" and "id" are of incompatible types: integer and uuid.',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'tablecmds.c',
line: '6503',
routine: 'ATAddForeignKeyConstraint' }
编辑:为了清楚起见,问题不在于为主键创建 UUID 字段,这是有效的。问题是我正在引用的表(在本例中为“views”)使用 UUID 主键,因此我还需要为引用它的字段使用 UUID(在本例中为“views”)。 TypeORM 自动创建具有整数类型的“view_id”字段,大概是因为它假定主键值将(应该?)总是整数(这让我觉得这是一个非常疯狂的假设)。
它必须是可配置的,不是吗?
【问题讨论】:
标签: node.js postgresql typescript nestjs typeorm