• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Relation 테이블 관련 에러

23.04.08 19:07 작성 조회수 335

0

Movie, User 테이블하고 many-to-many 로 만든 Favorite 테이블이 있는데
Favorite 테이블에 저장하려고 할 때 이런 에러가 납니다.

query failed: INSERT INTO `favorite`(`id`, `userId`, `movieId`) VALUES (DEFAULT, DEFAULT, DEFAULT)
error: Error: Unknown column 'id' in 'field list'
query: ROLLBACK
[Nest] 782975  - 04/08/2023, 6:59:26 PM   ERROR [ExceptionsHandler] Unknown column 'id' in 'field list'

 

Movie 는 이렇게 만들어져있구요

import { Entity, Column, PrimaryGeneratedColumn, ManyToMany, JoinTable } from 'typeorm';
import { User } from '../users/users.entity';

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

  @Column({ length: 100 })
  title: string;

  @Column('text', { nullable: true })
  desc: string;

  @ManyToMany(() => User, (user) => user.favorites)
  @JoinTable({ name: 'favorite' })
  favorites: User[];
}

User 는

import { Entity, Column, PrimaryGeneratedColumn, ManyToMany, JoinTable } from 'typeorm';
import { Movie } from '../movies/movies.entity';

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

  @Column()
  username: string;

  @ManyToMany(() => Movie)
  @JoinTable({ name: 'favorite' })
  favorites: Movie[];
}

그리고 Favorite 은

import { Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { User } from '../users/users.entity';
import { Movie } from '../movies/movies.entity';

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

  @ManyToOne(() => User, (user) => user.favorites)
  user: User;

  @ManyToOne(() => Movie, (movie) => movie.favorites)
  movie: Movie;
}

 

그런데 DB 를 보면 Favotie 테이블에 id 칼럼이 없습니다.

그래서 favoriteRepository.save() 할때 에러가 난다고 의심하고 있는데요, favorites.service.ts는

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Favorite } from './favorites.entity';

@Injectable()
export class FavoritesService {
  constructor(
    @InjectRepository(Favorite)
    private readonly favoriteRepository: Repository<Favorite>,
  ) {}

  async create(userId: number, movieId: number): Promise<Favorite> {
    const favorite = new Favorite();
    favorite.user = { id: userId } as any;
    favorite.movie = { id: movieId } as any;

    return await this.favoriteRepository.save(favorite);
  }
}

이렇게 되어있습니다.

어디를 고쳐야 하는걸까요?

답변 1

답변을 작성해보세요.

1

joinTable: 'favorite'이 class Favorite가 같다는 걸 typeorm이 알지 못합니다.

@Entity('favorite') 하세요

답변 감사합니다. 아 근데 지금 Many-to-many 를 안 쓰고 Favorite 쪽에서는 Many-to-one 으로 하고 User하고 Movie 쪽에서 One-to-many 로 스키마를 좀 바꿨는데 이렇게 해도 괜찮을까요?

네 그렇게도 가능합니다. 다만 조인을 두번해야할 뿐이죠