[英]How to save many to many relation in nestjs
I have two entities.我有两个实体。
Post entity
and Category entity
, which has ManyToMany
relation. Post entity
和Category entity
,具有ManyToMany
关系。 My question is how to save many to many relations.我的问题是如何保存多对多的关系。 What I did is I created a many-to-many relation in a way where we can add custom properties too.
我所做的是我以一种我们也可以添加自定义属性的方式创建了一个多对多关系。 For that I created
CategoryPost
entity which is the junction table for Post Entity
and Category Entity
为此,我创建了
CategoryPost
实体,它是Post Entity
和Category Entity
的连接表PostEntity.ts
import { CategoryPost } from "src/categoryAndPost/category-post.entity";
import { User } from "src/user/user.entity";
import { BaseEntity, Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
@Entity({name: 'post'})
export class PostEntity extends BaseEntity{
@PrimaryGeneratedColumn()
id: number
@Column()
body: string
@ManyToOne(() => User, (user: User) => user.posts, {eager: true})
@JoinColumn({name: 'user_id'})
user: User
@OneToMany(() => CategoryPost, categoriesPosts => categoriesPosts.post, {cascade: true})
categoriesPosts: CategoryPost[]
}
CategoryPost.ts
, which is junction for Category
and Post
Entities CategoryPost.ts
,这是Category
和Post
实体的交汇点
import { Category } from "src/category/category.entity";
import { PostEntity } from "src/post/post.entity";
import { BaseEntity, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
@Entity({name: 'category_post'})
export class CategoryPost extends BaseEntity{
@PrimaryGeneratedColumn()
id: number
@ManyToOne(() => PostEntity, post => post.categoriesPosts)
@JoinColumn({name: 'post_id'})
post: PostEntity
@ManyToOne(() => Category, category => category.categoriesPosts)
@JoinColumn({name: 'category_id'})
category: Category
}
Category.ts
import { CategoryPost } from "src/categoryAndPost/category-post.entity";
import { BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Category extends BaseEntity{
@PrimaryGeneratedColumn()
id: number
@Column()
label: string
@OneToMany(() => CategoryPost, categoriesPosts => categoriesPosts.category, {cascade: true})
categoriesPosts: CategoryPost[]
}
Now Category
table already consists of some values like React, Javascript, Python.现在
Category
表已经包含一些值,如 React、Javascript、Python。 Post can be related to one or more category.帖子可以与一个或多个类别相关。 So while creating a post I want to insert the post category too.
因此,在创建帖子时,我也想插入帖子类别。 So for that I did this.
所以为此我做了这个。
PostController.ts
import {Body, Controller, Get, Post} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm';
import { CategoryRepository } from 'src/category/category.repository';
import { UserRepository } from 'src/user/user.repository';
import { CreatePostDto } from './dto/create-post.dto';
import { PostEntity } from './post.entity';
import { PostService } from './post.service';
@Controller('/post')
@UseGuard(AuthGuard())
export class PostController{
constructor(private postService: PostService, @InjectRepository(UserRepository) private userRepository: UserRepository, @InjectRepository(CategoryRepository) private categoryRepository: CategoryRepository){}
@Post('/create')
async createPost(@Body() createPostDto: CreatePostDto, @getUser: user): Promise<PostEntity>{
const category1 = await this.categoryRepository.findOne({label: createPostDto.category1})
const category2 = await this.categoryRepository.findOne({label: createPostDto.category2})
return this.postService.createPost(createPostDto, user, category1, category2)
}
@Get()
async getPost(){
return this.postService.getPost()
}
}
PostService.ts
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { CreatePostDto } from "./dto/create-post.dto";
import { PostEntity } from "./post.entity";
import { PostRepository } from "./post.repository";
@Injectable()
export class PostService{
constructor(@InjectRepository(PostRepository) private postRepository: PostRepository){}
createPost(createPostDto: CreatePostDto, user, category1, category2): Promise<PostEntity>{
return this.postRepository.createPost(createPostDto, user, category1, category2)
}
async getPost(){
const post = await this.postRepository.findOne("3")
return post
}
}
PostRepository.ts
import { EntityRepository, Repository } from "typeorm";
import { CreatePostDto } from "./dto/create-post.dto";
import { PostEntity } from "./post.entity";
@EntityRepository(PostEntity)
export class PostRepository extends Repository<PostEntity>{
async createPost(createPostDto: CreatePostDto, user, category1, category2): Promise<PostEntity>{
const {body} = createPostDto
const post = new PostEntity()
post.body = body
post.user = user
post.categoriesPosts = [category1, category2]
await post.save()
return post
}
}
After doing做完之后
........
........
await post.save()
return post
It sends response as它发送响应为
{
"body": "post 8",
"user": {
"id": 1,
"username": "John"
},
"categoryPosts": [
{
"id": 4,
"label": "Javascript"
},
{
"id": 3,
"label": "React"
}
],
"id": 10
}
then in junction table, post_id gets saved but category_id, which is null
.然后在联结表中,post_id 被保存但 category_id,即
null
。
JunctionTable
id post_id category_id
1 10 null
2 10 null
Could anyone help me with this?谁能帮我解决这个问题?
its because you are saving all category object, change repository like this:这是因为您要保存所有类别 object,更改存储库如下:
PostRepository.ts PostRepository.ts
import { EntityRepository, Repository } from "typeorm";
import { CreatePostDto } from "./dto/create-post.dto";
import { PostEntity } from "./post.entity";
@EntityRepository(PostEntity)
export class PostRepository extends Repository<PostEntity>{
async createPost(createPostDto: CreatePostDto, user, category1, category2): Promise<PostEntity>{
const {body} = createPostDto
const post = new PostEntity()
post.body = body
post.user = user
post.categoriesPosts = [category1.id, category2.id] // Or "post.categoriesPosts = [category1.category_id, category2.category_id]" depend on your dto, it should be id of category
await post.save()
return post
}
}
If you have two entities and want to save both by a save method, you can use something like this(cascade: ['insert']):如果您有两个实体并希望通过保存方法保存两个实体,则可以使用类似这样的内容(cascade: ['insert']):
Post.entity.ts Post.entity.ts
@OneToMany(() => CategoriesPosts, (categoriesPosts) => categoriesPosts.post, {
eager: false,
cascade: ['insert'],
})
categoriesPosts: categoriesPosts[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.