【问题标题】:NestJS - TypeORM - ManyToOne Entity is undefinedNestJS - TypeORM - 多对一实体未定义
【发布时间】:2020-09-03 08:40:19
【问题描述】:

我正在尝试链接到实体 ChildClient

所以我创建了 2 个实体:

// src/children/child.entity.ts

@Entity()
export class Child extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstname: string;

  @Column()
  lastname: string;

  @ManyToOne(type => Client, client => client.children, { eager: false })
  client: Client

  @Column()
  clientId: number;
}

// src/clients/client.entity.ts

@Entity()
export class Client extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstname: string;

  @Column()
  lastname: string;

  @OneToMany(type => Child, child => child.client, { eager: true })
  children: Child[];

}

我可以创建一个client 和一个child。当我得到一个client 时,我可以检索他所有的children

但我无法用child 检索client

例如,在children.controller.ts

当我访问http://locahost:3000/children/1/parent

我上了控制台:

我真的被卡住了,因为我不知道如何解决这个问题。

这里是children.module.ts

import { Module } from '@nestjs/common';
import { ChildrenController } from './children.controller';
import { ChildrenService } from './children.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ChildRepository } from './child.repository';
import { ClientRepository } from 'src/clients/client.repository';
import { ClientsService } from 'src/clients/clients.service';
import { Client } from 'src/clients/client.entity';

@Module({
  imports: [
    TypeOrmModule.forFeature([ChildRepository, ClientRepository, Client]),
  ],
  controllers: [ChildrenController],
  providers: [ChildrenService, ClientsService]
})
export class ChildrenModule {}

这里是typeorm.config

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export const typeOrmConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'myusername',
  password: '',
  database: 'mydatabase',
  entities: [__dirname + '/../**/*.entity.{js,ts}'],
  synchronize: true,
}

编辑 1:

children.controller.ts

// src/children/children.controller.ts

@Controller('children')
export class ChildrenController {

  constructor(
    private childrenService: ChildrenService,
    private clientsService: ClientsService
  ) {}

  @Get('/:id')
  async getChild(id: number): Promise<Child> {
    return await this.childrenService.getChild(id);
  }
}

children.service.ts

// src/children/children.service.ts

@Injectable()
export class ChildrenService {
  constructor(
    @InjectRepository(ChildRepository)
    private childRepository: ChildRepository,
    @InjectRepository(ClientRepository)
    private clientRepository: ClientRepository
  ) {}

  async getChild(id: number): Promise<Child> {
    return await this.childRepository.findOne(id)
  }
}

谢谢你的帮助????

【问题讨论】:

  • 什么代码包含你的getChild方法?
  • 我已经添加了 getChild 的代码以将孩子检索到数据库中。

标签: typescript entity nestjs typeorm many-to-one


【解决方案1】:

在我看来,您忘记在此关系的 ManyToOne 端添加 @JoinColumn()。尝试以这种方式增强您的代码


@Entity()
export class Child extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstname: string;

  @Column()
  lastname: string;

  @ManyToOne(type => Client, client => client.children, { eager: false })
  @JoinColumn()
  client: Client

  @Column()
  clientId: number;
}

另外,请注意eager 参数。如果它设置为true,即使您不需要手动加载此关系也会自动加载,否则您必须指定要加载关系。 尝试像这样增强children.service.ts

  async getChild(id: number): Promise<Child> {
    return await this.childRepository.findOne(id, {
      relations: ['client']
    })
  }

或者您可以将此关系设置为eager,每次加载Child时都会自动加载

  @ManyToOne(type => Client, client => client.children, { eager: true })
  @JoinColumn()
  client: Client

【讨论】:

  • 感谢您的回答!我仍然有这个问题。更新后我重新启动了服务器。不工作 + 我删除了数据库表,但仍然不工作。
  • 更改数据库后,您需要生成迁移并应用它
  • 我很抱歉,但我不知道如何进行。我以为synchronize: true 一切都会自动更新
  • synchronize: true 是对的。我在回答中又添加了一条建议,试试吧
  • 添加{ relations: ['client'] } 解决了这个问题!非常感谢!
【解决方案2】:

正如@Yevhenii 提到的,您忘记添加 JoinColumn 但您必须指定客户列:

    @Entity()
export class Child extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstname: string;

  @Column()
  lastname: string;

  @ManyToOne(()=> Client, (client) => client.children, { eager: false })
  @JoinColumn([{ name: "clientId", referencedColumnName: "id" }])
  client: Client

  @Column()
  clientId: number;
}

不要犹豫,告诉我结果。

【讨论】:

  • 感谢您的回答。 Yevhenii 给出的解决方案效果很好。
猜你喜欢
  • 2022-01-17
  • 2021-02-22
  • 2020-11-14
  • 1970-01-01
  • 2019-11-13
  • 2020-08-29
  • 2022-01-02
  • 2020-09-01
  • 2021-04-23
相关资源
最近更新 更多