Search code examples
nestjstypeorm

TypeOrm Error : Relation with property path xxx in entity was not found


I am new with TypeOrm and Nestjs and Mysql ,

and this is Order entity

@Entity()
export class Order {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => Media, (media) => media.id, { eager: false })
    media: Media


    @Column({ type: 'enum', enum: OrderStatus, default: OrderStatus.WAITING })
    status: OrderStatus

    @ManyToOne(() => User, (user) => user.id)
    @JoinColumn({ name: 'ownerId' })
    owner: User

    @ManyToOne(() => User, (user) => user.id)
    @JoinColumn({ name: 'clientId' })
    client: User

    @Column()
    description: string

    @Column({ nullable: true, default: null })
    score: number | null

    @CreateDateColumn({ type: 'timestamp' })
    createdAt: Date;

    @UpdateDateColumn({ type: 'timestamp' })
    updatedAt: Date

    @DeleteDateColumn()
    deletedAt: Date

    @BeforeUpdate()
    private validateScore() {
        if (this.score !== null && (this.score < 0 || this.score > 100)) {
            throw new Error('Score must be between 0 and 100');
        }
    }
}

and this is user entity

import { Role } from 'src/common/authorization/role.enum';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  email: string;

  @Column()
  password: string;

  @Column({ default: Role.User })
  role: Role;

  @Column({ default: null })
  verifiedAt: Date | null

}

and this is service that return all orders

  async findAll(role: Role, query: GetOrdersQueryDto) {

    const page = query.page || 1;
    const itemPerPage = query.item_per_page || 10;

    const theQuery = this.orderRepository.createQueryBuilder('order')


    const [data,totalCount]=await theQuery
    .leftJoinAndSelect('order.owner ','user') // error happens here
    .leftJoinAndSelect('order.client','user')
    .orderBy('order.createdAt')
    .skip((page-1)*itemPerPage)
    .take(itemPerPage)
    .getManyAndCount()

    return {
      data,
      pagination: { total_count: totalCount, item_per_page: itemPerPage, page },
    };
  }

and the problem is here , when I want to leftjoin

.leftJoinAndSelect('order.owner ','user')

I get error

Relation with property path owner in entity was not found.

But as you can see in order entity , there is many-to-one relation between owner and user entity

both client and owner are foreign key of user .

and it is so strange that there is no problem with client

so , what's the problem and how can I fix this ?


Solution

  • you are using the same alias (user) for both joins and TypeORM can not differentiate between the two relationships. To solve this you need to use different aliases for each leftJoinAndSelect like:

      .leftJoinAndSelect('order.owner', 'owner')
      .leftJoinAndSelect('order.client', 'client')