Search code examples
typescriptnestjstypeorm

How add relationship data?


When i tryed save - i have null on relation column

how i can save this relation data?

Entity:

@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;
}

I cant resolve this probblem, who can help with this?


Solution

  • I don't think this is an issue with your entity. More than likely an issue with your query. When saving relationships, they're not automatically queried from the repository.

    Take a look at this https://typeorm.io/#/undefined/loading-objects-with-their-relations

    you'll notice that there is a key called relations. This is where you specify that you want to join your user. For example

    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'],
        });
      }
    }
    

    This should now fetch your project entity with the relation user if a user has been assigned. Hope this helps!