I have two entities. Post entity
and Category entity
, which has ManyToMany
relation. 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
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
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. 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
.
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:
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']):
Post.entity.ts
@OneToMany(() => CategoriesPosts, (categoriesPosts) => categoriesPosts.post, {
eager: false,
cascade: ['insert'],
})
categoriesPosts: categoriesPosts[];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.