我有一个使用TypeORM和PostgreSQL数据库的类型记录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字段,而是在工作。问题是,我所引用的表(在本例中为“视图”)使用了一个UUID主键,因此我需要使用UUID作为引用它的字段(本例中为“视图”)。TypeORM自动创建具有整数类型的"view_id“字段,大概是因为它假定主键值将(应该吗?)总是整数(在我看来,这是一个非常疯狂的假设)。
它必须是可配置的,不是吗?
发布于 2019-01-21 09:40:54
最后,我找到了这个问题的解决方案,我将在这里发布它,供以后参考。
以下几点对我来说是可行的:
export class AgentKitsEntity implements Model {
@PrimaryGeneratedColumn('uuid')
@Generated('uuid')
id: string;
}
@Entity({name: 'users'})
export class User extends AgentKitsEntity implements UserModel {
@Column()
username: string;
@ManyToOne(type => View, { nullable: true })
@JoinColumn({name: 'view_id'})
view: View;
}似乎解决了这个问题的关键区别在于,我在@PrimaryGeneratedColumn()装饰器中指定了'uuid‘。这是令人惊讶的,因为字段实际上是以UUID的形式在数据库中正确地创建的,但是似乎TypeORM假设关键字段是整数,除非您显式地指定类型,即使它知道如何为字段本身创建正确的数据类型。
编辑:仔细检查后,发现@Generated('uuid')实体是多余的,因此上面基类的代码可以简化为:
export class AgentKitsEntity implements Model {
@PrimaryGeneratedColumn('uuid')
id: string;
}https://stackoverflow.com/questions/54280856
复制相似问题