Class 05: Quan hệ trong Database (OneToMany, ManyToOne) với TypeORM
Thiết lập quan hệ giữa bảng: user – post
Entity User
// users/entities/user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Post } from '../../posts/entities/post.entity';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Post, post => post.user, { cascade: true })
posts: Post[];
}Entity Post
Giải thích cú pháp
Cascade và Eager Loading
Cascade
Eager Loading
Repository query nâng cao
Cách 1: dùng relations trong find
relations trong findCách 2: dùng QueryBuilder
QueryBuilderThực hành: API lấy user kèm danh sách bài viết
Mục tiêu
Yêu cầu
Gợi ý controller
Gợi ý service
Output mong muốn
Bài tập thực hành
Mục tiêu
Yêu cầu bài tập
Kết luận
Last updated