簡體   English   中英

在 Nest JS / TypeORM 中使用具有關系的實體內部的實體並填充數據庫

[英]Using entity inside entity with relationships and populating database in Nest JS / TypeORM

假設我們正在為新的 web 應用程序構建我們的第一個實體。 用戶有一個實體

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  password: string;

  @OneToOne(() => Author)
  author: Author;

用戶注冊后可以成為作者 所以用戶和作者表之間存在一對一的關系。 假設我們有另一個名為 books 的表,一個作者可以有多本書。

export class Author {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  Name: string;

  @OneToMany(() => Book, (Book) => Book.Author)
  Book: Book[];

  @OneToOne(() => User)
  @JoinColumn()
  User: User;

這是 Books 存儲庫的示例實體:

export class Book {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  Name: string;

  @Column()
  ISIN: string;

  @OneToOne(() => Author)
  @JoinColumn()
  Author: Author;

問題是,當我們遷移這些實體並構建我們的第一個/干凈的數據庫時,我們如何通過調用 API插入數據 API Post 方法的示例服務:

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book)
    private BookRepository: Repository<Book>,
  ) {}
  async create(createBookDto: CreateBookDto) {
    await this.BookRepository.insert(createBookDto);
  }
}

Controller:

@Controller('books')
export class BookController {
  constructor(private readonly BookService: BookService) {}

  @Post('/Book')
  create(@Body() createBookDto: CreateBookDto) {
    return this.BookService.create(createBookDto);
  }
}

這里的問題是,當我想通過 POST 數據到 API 路由來創建新書時,需要定義作者。 那么如何通過此服務將現有的用戶書籍作者數據發布到數據庫中呢?
我認為最好的選擇是創建classes 的新實例,請求 @Body獲取數據並將其分配給 class 的對象,然后將其保存到數據庫中。
但我認為這不是一個好的解決方案,因為它非常喜歡使用存儲庫而不是對象類類型。

我認為您在實體定義中犯了一個錯誤。 Author 與 Book 之間存在 OneToMany 關系。

像這樣修改您的圖書實體

export class Book {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  Name: string;

  @Column()
  ISIN: string;

  @ManyToOne(() => Author, author=> author.book, { nullable: true })
  @JoinColumn()
  Author: Author;

{ nullable: true }這將允許您在沒有作者的情況下保存您的圖書數據。

修改您的服務以保存圖書信息

public async create(createBookDTO: CreateBookDTO) {
        try {
            if (
                createBookDTO.hasOwnProperty('author') &&
                createTaskDTO.author
            ) {
                const author = await this.connection.manager.findOne(Author, {
                    where: {
                        id: createBookDTO.author,
                    },
                });
                if (author) {
                    createBookDTO.author = author;
                } else {
                    throw new NotAcceptableException('Author not found');
                }
            }

            return await this.bookRepo.save(createBookDTO);
        } catch (err) {
            throw new HttpException(err, err.status || HttpStatus.BAD_REQUEST);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM