Search code examples
typeormnestjs-typeorm

I am unable to retrieve the Many-To-One column while fetching records


Here is entity code

 @ManyToOne(() => UserEntity, (user) => user.id)
      @JoinColumn({ name: 'user_id' })
      user_id: number;

I've tried this code

PropertyEntity.find({relations: ['user_id']})

Solution

  • Your entity definition is wrong. @ManyToOne decorator should decorate a field that is of type User. Try this:

    @ManyToOne(() => UserEntity, (user) => user.id)
    @JoinColumn({ name: 'user_id' }) // This would be the join column name in the table in Postgres
    user: User;
    
    /**
     * The following is optional. You can omit this property and it would still 
     * work. Keeping this helps if you want to insert this record without 
     * providing the entire `User` entity. This also allows you to find using 
     * `user_id`.
     *
     * Note: Change the type if it is not `varchar`.
     */
    @Column({ type: 'varchar' })
    user_id: string;
    

    Then when you want to find, you should use the below syntax in your find method:

    find({ relations: ['user'] });