网站搜索

mysql - EntityPropertyNotFoundError Typeorm 关系 查找


动机

我在使用 Typeorm 的 find 选项加载关联时遇到了错误。
代码类似于 Typeorm 文档中的示例,但似乎不起作用。

Typeorm 仓库使用关联选项进行查找

await this.userRepository.findOneOrFail({
  where: { id },
  relations: { 
    cursos: { 
      nome: true 
    }
  },
});

关系

  • 用户
@Entity({ name: 'users' })
export class Users {
  @PrimaryGeneratedColumn()
  id: number;

  @Columns()
  nome: string;

  @OneToMany(() => Courses, (course) => course.user)
  cursos: Courses[];
}
  • 课程
@Entity({ name: 'cursos' })
export class Courses {
  @PrimaryColumn({ nullable: false })
  id: number;

  @Column()
  nome: string;

  @Column()
  user_id: number;

  @ManyToOne(() => Users, (user) => user.cursos)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: Users;
}

预期

{
  "id": 1,
  "nome": "Rogerio",
  "cursos": [
    {
      "nome": "BACHARELADO EM ENG DE COMPUTAÇÃO"
    }
  ]
}

错误

[ExceptionsHandler] Property "nome" was not found in "Courses". Make sure your query is correct.
EntityPropertyNotFoundError: Property "nome" was not found in "Courses". Make sure your query is correct.

答案#1

我刚刚弄明白了如何绕过这个问题,使用关系外的选择选项

await this.userRepository.findOneOrFail({
  where: { id },
  relations: { cursos: true },
  select: { cursos: { id: true, nome: true }
});