'TypeORM OneToMany and ManyToOne relations cases 500 error on GET request

After adding OneToMany and manyToOne relations in the entities and doing GET request it shows in postman 500 error.

// Car entity

@Entity({ name: 'car' })
export class Car {
  @PrimaryColumn()
  car_id: number;
  @Column()
  name: string;
  @Column()
  enabled: boolean;

  @ManyToOne(() => Person, (person) => person.cars)
  person: Person;
}

// Person entity

@Entity({ name: 'person' })
export class Person {
  @PrimaryColumn()
  person_id: number;

  @Column()
  name: string;

  @Column()
  enabled: boolean;

  @OneToMany(() => Car, (car) => car.person)
  cars: Car[];
}

// Postman

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/api/v2/cars",
    "method": "GET",
}

UPDATE In try catch it shows this error

ERROR QueryFailedError: column Car.personPersonId does not exist

//Service GET request to fetch cars by person id

async getByPersonId(
    personId: string | number,
    relations: string[] = [],
    throwsException = false,
  ): Promise<Car[] | []> {
    return await this._carRepository.getByPersonId(
      personId,
      relations,
      throwsException,
    );
  }

// Repository

async getByPersonId(
    personId: string | number,
    relations: string[] = [],
    throwsException = false,
    enabled?: boolean,
  ): Promise<Car[]> {
    const where: IPersonById = {
      person_id: personId,
    };

    if (!isNil(enabled)) {
      where.enabled = enabled;
    }

    return await this.find({
      where: {
        ...where,
      },
      relations,
    })
      .then((entities) => {
        if (!entities && throwsException) {
          return Promise.reject(
            new NotFoundException(
              'Car is not found by provided person id.',
            ),
          );
        }

        return Promise.resolve(entities ? this.transformMany(entities) : null);
      })
      .catch((error) => {
        console.log('ERROR', error);
        return Promise.reject(error);
      });
  }


Solution 1:[1]

Try this:

on the Car entity:

@ManyToOne(type => Person, person => person.cars, {eager: false})
    person: Person

on the Person Entity

@OneToMany(type => Car, car => car.person, {eager: true})
    cars: Car[];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ardritkrasniqi