node.js - TypeScript,TypeORM,@OneToMany:构造函数根本不起作用
我正在尝试使用 node.js、typescript 和 typeorm 创建两个实体,它们之间存在一对多的关系。相关的实体是“Movie”和“MovieVote”。代码如下。
电影实体:
import {Column, Entity, JoinColumn, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import { ApiModel, ApiModelProperty } from 'swagger-express-ts';
import { MovieVote } from "~/entities/MovieVote";
import { Genre } from './Genre';
@Entity()
@ApiModel({
description: 'The movie entity.',
name: 'Movie',
})
export class Movie {
@PrimaryGeneratedColumn()
id?: number;
@Column({ length: 50 })
@ApiModelProperty({
description: 'The title of the movie',
})
title: string;
@Column({ length: 250 })
@ApiModelProperty({
description: 'The description of the movie',
})
description: string;
@Column({ length: 50 })
@ApiModelProperty({
description: 'The director of the movie',
})
director: string;
@Column({ enum: Genre, type: 'enum' })
@ApiModelProperty({
description: 'The genre of the movie',
})
genre: Genre;
@OneToMany(() => MovieVote, movieVote => movieVote.movie)
votes: MovieVote[];
constructor(title: string, description: string, director: string, genre: Genre) {
this.title = title;
this.description = description;
this.director = director;
this.genre = genre;
this.votes = [];
}
}
MovieVote 实体:
import {Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn} from 'typeorm';
import { ApiModel, ApiModelProperty } from 'swagger-express-ts';
import { User } from "~/entities/User";
import { Movie } from "~/entities/Movie";
@Entity()
@ApiModel({
description: 'The movie vote entity.',
name: 'MovieVote',
})
export class MovieVote {
@PrimaryGeneratedColumn()
id?: number;
@Column()
@ApiModelProperty({
description: 'The vote value'
})
value: number;
@ManyToOne(() => User)
@ApiModelProperty({
description: 'The user responsible for the vote'
})
user: User;
@ManyToOne(() => Movie, movie => movie.votes)
// @ApiModelProperty({
// description: 'The movie the user has voted on'
// })
@JoinColumn({name : 'movieId'})
movie: Movie;
constructor(user: User, movie: Movie, value: number) {
this.value = value;
this.user = user;
this.movie = movie;
}
}
发生的情况是,当我尝试运行代码时,它给了我以下错误:
启动服务器时出错,错误:实体关系中不允许数组初始化。请从 "Movie#votes" 中移除数组初始化 (= [])。这是 ORM 的要求,以确保关系正常工作。有关更多信息,请参考文档。
问题似乎出在 Movie 实体的构造函数中。我无法在实体中使用 "= [];" 来初始化关系 "votes",但我不知道应该怎样做。此外,typeorm 的文档中基本没有提到这一点。
为什么在整个文档中没有这种类型的 OneToMany 关系的实体构造函数示例,这让我无法理解,但我先不说这个。任何帮助都会受欢迎,提前谢谢!
附注:我已在 MovieVote 上注释了 @ApiModelProperty 注解,因为出于某些未知原因,这也会导致“_decorator 错误”和一些与未定义属性相关的问题。
答案#1
问题是 this.votes=[]。
通常,实体的构造函数不传入任何值,也不应设置任何值。TypeORM 会为你处理所有创建工作。
如果你需要能够使用 new 来构造类的实例,你可以像我一样做,并将其更改为如下内容。
constructor(title?: string, description?: string, director?: string, genre?: Genre) {
if (title) {
this.title = title;
this.description = description;
this.director = director;
this.genre = genre;
this.votes = [];
}
}
