add relations

This commit is contained in:
Ken Yasue
2025-06-01 22:36:04 +02:00
parent 5149012dcf
commit 8671a058be
7 changed files with 476 additions and 20 deletions

View File

@ -0,0 +1,34 @@
import { Column, Entity, ManyToOne, ManyToMany, JoinColumn, JoinTable, type Relation } from "typeorm"
import { UserEntity } from "./UserEntity"
import { TagEntity } from "./TagEntity"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
@Entity({ name: "posts" })
export class PostEntity extends AbstractBaseEntity {
@Column({ type: "text" })
content!: string
@Column({ type: "varchar" })
userEmail!: string
@Column({ type: "varchar" })
username!: string
@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
createdAt!: Date
@ManyToOne(() => UserEntity, { nullable: true })
@JoinColumn({ name: "userEmail", referencedColumnName: "email" })
user!: Relation<UserEntity> | null
@ManyToMany(() => TagEntity, (tag) => tag.posts)
@JoinTable({
name: "post_tags",
joinColumn: { name: "postId", referencedColumnName: "id" },
inverseJoinColumn: { name: "tagId", referencedColumnName: "id" }
})
tags!: TagEntity[]
}
export default PostEntity

View File

@ -0,0 +1,18 @@
import { Column, Entity, ManyToMany } from "typeorm"
import { PostEntity } from "./PostEntity"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
@Entity({ name: "tags" })
export class TagEntity extends AbstractBaseEntity {
@Column({ type: "varchar", unique: true })
name!: string
@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
createdAt!: Date
@ManyToMany(() => PostEntity, (post) => post.tags)
posts!: PostEntity[]
}
export default TagEntity

View File

@ -3,9 +3,10 @@ import SessionEntity from "./SessionEntity"
import AccountEntity from "./AccountEntity"
import { transformer } from "../utils/transformers"
import AbstractBaseEntity from "./abstract/AbstractBaseEntity"
import { PostEntity } from "./PostEntity"
@Entity({ name: "users" })
export class UserEntity extends AbstractBaseEntity {
export class UserEntity extends AbstractBaseEntity {
@Column({ type: "varchar", nullable: true })
name!: string | null
@ -30,4 +31,7 @@ export class UserEntity extends AbstractBaseEntity {
@OneToMany(() => AccountEntity, (account) => account.userId)
accounts!: Relation<AccountEntity>[]
}
@OneToMany(() => PostEntity, (post) => post.user)
posts!: Relation<PostEntity>[]
}