Y
Y
yaroslav19962022-01-26 23:28:17
PostgreSQL
yaroslav1996, 2022-01-26 23:28:17

How to correctly update Entity with relation oneToMany @nestjs/typeorm pg driver?

Hello everyone, dear friends! Please tell me, there is a problem with updating relations in entity.

An example of a coach entity:

@Entity()
export class Trainer {
  @OneToMany(() => Social, (social: Social) => social.trainer, {
    cascade: true,
  })
  socials: Social[];
}


An example of a social network entity:

@Entity()
export class Social {
  @ManyToOne(() => Trainer, (trainer) => trainer.socials)
  trainer: Trainer;
}


When created, everything works correctly using the following code:

const trainer = this.trainerRepository.create(createTrainerInput);
      await this.trainerRepository.save(trainer);


When using the update method, I get the following error:

Error: Cannot query across one-to-many for property socials
    at _loop_4 (D:\starsup\src\query-builder\QueryBuilder.ts:1030:27)
    at UpdateQueryBuilder.QueryBuilder.createPropertyPath (D:\starsup\node_modules\typeorm\query-builder\QueryBuilder.js:907:17)
    at UpdateQueryBuilder.createUpdateExpression (D:\starsup\src\query-builder\UpdateQueryBuilder.ts:387:18)
    at UpdateQueryBuilder.getQuery (D:\starsup\src\query-builder\UpdateQueryBuilder.ts:48:21)
    at UpdateQueryBuilder.QueryBuilder.getQueryAndParameters (D:\starsup\src\query-builder\QueryBuilder.ts:446:28)
    at UpdateQueryBuilder.<anonymous> (D:\starsup\src\query-builder\UpdateQueryBuilder.ts:106:50)
    at step (D:\starsup\node_modules\tslib\tslib.js:143:27)
    at Object.next (D:\starsup\node_modules\tslib\tslib.js:124:57)
    at fulfilled (D:\starsup\node_modules\tslib\tslib.js:114:62)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)


This solution creates a new element instead of updating:

const trainer = await this.trainerRepository.findOne({ id });

    for (const [key, value] of Object.entries(updateTrainerInput)) {
      trainer[key] = value;
    }

    await this.trainerRepository.save(trainer);


How to solve the problem correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question