【问题标题】:How add relationship data?如何添加关系数据?
【发布时间】:2019-11-24 04:36:48
【问题描述】:

当我尝试保存时 - 我在关系列上有 null

如何保存这些关系数据?

实体:

@Entity('project')
export class Project {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar')
  name: string;

  @Column('varchar')
  description: string;

  @Column()
  createdAt: Date;

  @ManyToOne(type => User)
  @JoinColumn({ referencedColumnName: 'id' })
  user: User|number;
}

Dto:

export class CreateProjectDto {
  readonly id: number;
  readonly name: string;
  readonly description: string;
  readonly createdAt: Date;
  readonly user: User|number;
}

我无法解决这个问题,谁能帮忙解决这个问题?

【问题讨论】:

    标签: typescript nestjs typeorm


    【解决方案1】:

    我认为这与您的实体无关。您的查询很可能有问题。保存关系时,不会自动从存储库中查询它们。

    看看这个https://typeorm.io/#/undefined/loading-objects-with-their-relations

    您会注意到有一个名为relations 的键。这是您指定要加入用户的地方。例如

    import {Injectable} from '@nestjs/common';
    import {Repository} from 'typeorm';
    import {InjectRepository} from '@nestjs/typeorm';
    import Project from './project.entity';
    
    @Injectable()
    export class ProjectService {
      constructor(@InjectRepository(Project) private readonly projectRepository: Repository<Project>) {}
    
      async findOne(id: number): Promise<Project | null> {
        return await this.projectRepository.findOne({
          where: {
            id,
          },
          relations: ['user'],
        });
      }
    }
    

    如果已分配用户,现在应该使用关系用户获取您的项目实体。希望这可以帮助!

    【讨论】:

    • 如何从用户关系中获取用户名。它不允许直接获取 projectRepository.user.username。在 JSON.parse(JSON.stringify(projectRepository)) 之后,它才成为一个普通的对象。对此有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多