在实体PostsEntity中找不到未定义的引用列

时间:2020-03-10 13:52:10

标签: typeorm

我正在尝试使用NestJS和TypeORM在2个表之间设置n-1关系,但是我得到了:Referenced column undefined was not found in entity PostsEntity。我不知道为什么,在互联网上也找不到与此错误有关的帖子。

我的实体:

@Entity('appreciations')
export class AppreciationsEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    postId: number;

    @Column()
    userId: number;

    @Column()
    value: boolean;

    @ManyToOne(type => PostsEntity)
    @JoinColumn([
        { name: 'postId' },
        { name: 'userId', referencedColumnName: 'userId' }
    ])
    post: PostsEntity;
}

@Entity('posts')
export class PostsEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    content: string;

    @Column()
    userId: number;

    @ManyToOne(type => UsersEntity, user => user.posts)
    user: UsersEntity;

    @OneToMany(type => AppreciationsEntity, appreciation => appreciation.post)
    @JoinColumn()
    appreciations: AppreciationsEntity[];
}

怎么了?

2 个答案:

答案 0 :(得分:0)

这里有2个问题。

JoinColumn

首先,JoinColumn不正确

通常,引用的列默认为相关实体的主列。

来自TypeORM doc:

默认情况下,您的关系始终引用相关实体的主列。

但是,使用多列时并非如此:必须提供引用的列名。

所以代替这个:

@ManyToOne(type => PostsEntity)
@JoinColumn([
    { name: 'postId' }, // I expected referencedColumnName to default to 'id'
    { name: 'userId', referencedColumnName: 'userId' }
])
post: PostsEntity;

我应该有这个:

@ManyToOne(type => PostsEntity)
@JoinColumn([
    { name: 'postId', referencedColumnName: 'id' },
    { name: 'userId', referencedColumnName: 'userId' }
])
post: PostsEntity;

索引

创建外键需要相关实体上的目标列具有索引。

来自this answer on SO

定义外键时,MySQL要求远程表中的列上存在索引

没有包含主键id和列userId的索引,因此我必须提供它:

@Entity('posts')
@Index(['id', 'userId'])
export class PostsEntity {
    ...
}

答案 1 :(得分:0)

TypeORM 似乎在您的 PostsEntity 实体上找不到 userId 属性。 关于它的关于列关系的文档 here,它在 AppreciationsEntity 上应该是这样的:

@ManyToOne(
  (): ObjectType<PostsEntity> => PostsEntity,
  ({ appreciations }): AppreciationsEntity[] => appreciations,
)
@JoinColumn([
  { name: 'postId', referencedColumnName: 'id' },
  { name: 'userId', referencedColumnName: 'userId' },
])
post: PostsEntity;

在 PostsEntity 上应该是这样的:

@OneToMany(
  (): ObjectType<AppreciationsEntity> => AppreciationsEntity,
  ({ post }): PostsEntity => post,
)
appreciations: AppreciationsEntity[];