TypeORM关系和表达式



我正在与TypeORM和MySQL以及Express建立多对一,一对多关系。有两个表冷岗位和用户。一个用户有多个帖子。每个帖子有一个用户。我想使用'userUuid'列作为连接这两个表的外键。有人能告诉我怎么修吗?

谢谢

//user

import {
Entity,
PrimaryGeneratedColumn,
Column,
BaseEntity,
BeforeInsert,
Generated,
OneToMany,
} from 'typeorm'
import { v4 as uuid } from 'uuid'

import { Post } from './Post'
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id!: number

@Column()
userId!: string

@Column()
@Generated('uuid')
userUuid!: string

@Column({ nullable: true })
displayName!: string

@Column({ nullable: true })
email!: string

@OneToMany(() => Post, (post: Post) => post.user)
posts!: Post[]

@BeforeInsert()
createUuid() {
this.userUuid = uuid()
}

toJSON() {
return { ...this, id: undefined }
}
}

//后

import {
Entity,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Column,
BaseEntity,
Generated,
BeforeInsert,
ManyToOne,
JoinColumn,
} from 'typeorm'
import { v4 as uuid } from 'uuid'
import { User } from './User'
@Entity()
export class Post extends BaseEntity {
@PrimaryGeneratedColumn()
id!: number

@Column()
@Generated('uuid')
postUuid!: string

@Column({ nullable: true })
userUuid!: string

@CreateDateColumn({ nullable: true })
createdAt!: Date

@UpdateDateColumn({ nullable: true })
updatedAt!: Date

@Column({ nullable: true })
content!: string

@BeforeInsert()
createUuid() {
this.postUuid = uuid()
}

@ManyToOne(() => User, (user: User) => user.posts)
user!: User

@JoinColumn([{ name: 'userUuid' }, { referencedColumnName: 'userUuid' }])
toJSON() {
return { ...this, id: undefined }
}
}

//

表达
router
.route('/')
.get((req: Request, res: Response) => {
User.find({ relations: ['posts'] })
.then((data) => {
res.send(data)
})
.catch((err) => res.send(err))
})

//

表达
router
.route('/')
.get((req: Request, res: Response) => {
Post.find({ relations: ['user'] })
.then((data) => {
res.send(data)
})
.catch((err) => res.send(err))
})         

似乎你需要使用JoinColumn装饰器。

class Post /*...*/ {
/*...*/
@ManyToOne(() => User)
@JoinColumn({ referencedColumnName: "userUuid" })
userUuid!: string;
/*...*/
}

From TypeORM docs

连接列总是对其他列的引用(使用外键)。默认情况下,关系总是引用相关实体的主列。如果你想与相关实体的其他列创建关系,你也可以在@JoinColumn中指定它们:

@ManyToOne(type => Category)
@JoinColumn({ referencedColumnName: "name" })
category: Category;

关系现在引用Category实体的名称,而不是id。该关系的列名将变为categoryName。

相关内容

  • 没有找到相关文章

最新更新