add relations

This commit is contained in:
liuyi 2025-05-20 13:10:19 +08:00
parent e487cf7555
commit a7b685b2e1
4 changed files with 46 additions and 3 deletions

View File

@ -1,4 +1,6 @@
import { Column, Entity, PrimaryColumn } from 'typeorm';
import { Column, Entity, OneToMany, PrimaryColumn, Relation } from 'typeorm';
import { PostEntity } from '@/modules/content/entities/post.entity';
@Entity('content_category')
export class CategoryEntity {
@ -10,4 +12,7 @@ export class CategoryEntity {
@Column({ comment: '分类排序', default: 0 })
customOrder: number;
@OneToMany(() => PostEntity, (post) => post.category, { cascade: true })
posts: Relation<PostEntity[]>;
}

View File

@ -1,4 +1,6 @@
import { Column, CreateDateColumn, Entity, PrimaryColumn } from 'typeorm';
import { Column, CreateDateColumn, Entity, ManyToOne, PrimaryColumn, Relation } from 'typeorm';
import { PostEntity } from '@/modules/content/entities/post.entity';
@Entity('content_comment')
export class CommentEntity {
@ -10,4 +12,11 @@ export class CommentEntity {
@CreateDateColumn({ comment: '创建时间' })
createdAt: Date;
@ManyToOne(() => PostEntity, (post) => post.comments, {
nullable: false,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
})
post: Relation<PostEntity>;
}

View File

@ -4,11 +4,18 @@ import {
Column,
CreateDateColumn,
Entity,
JoinTable,
ManyToMany,
OneToMany,
PrimaryColumn,
Relation,
UpdateDateColumn,
} from 'typeorm';
import { PostBodyType } from '@/modules/content/constants';
import { CategoryEntity } from '@/modules/content/entities/CategoryEntity';
import { CommentEntity } from '@/modules/content/entities/comment.entity';
import { TagEntity } from '@/modules/content/entities/tag.entity';
@Exclude()
@Entity('content_posts')
@ -55,4 +62,19 @@ export class PostEntity extends BaseEntity {
@Type(() => Date)
@UpdateDateColumn({ comment: '更新时间', nullable: true })
updatedAt?: Date;
@Expose()
@OneToMany(() => CategoryEntity, (category) => category.posts, {
nullable: true,
onDelete: 'SET NULL',
})
category: Relation<CategoryEntity>;
@Expose()
@ManyToMany(() => TagEntity, (tag) => tag.posts, { cascade: true })
@JoinTable()
tags: Relation<TagEntity[]>;
@OneToMany(() => CommentEntity, (comment) => comment.post, { cascade: true })
comments: Relation<CommentEntity[]>;
}

View File

@ -1,4 +1,7 @@
import { Column, Entity, PrimaryColumn } from 'typeorm';
import { Expose } from 'class-transformer';
import { Column, Entity, ManyToMany, PrimaryColumn, Relation } from 'typeorm';
import { PostEntity } from '@/modules/content/entities/post.entity';
@Entity('content_tag')
export class TagEntity {
@ -10,4 +13,8 @@ export class TagEntity {
@Column({ comment: '标签描述', nullable: true })
desc?: string;
@Expose()
@ManyToMany(() => PostEntity, (post) => post.tags)
posts: Relation<PostEntity[]>;
}