question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

findOne for a ManyToOne relationship

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

I am trying to findOne with a where in a related entity, but I can’t.

@Entity()
export class UserEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ length: 20 })
  username: string

  @OneToMany(() => GameMemberEntity, gameMember => gameMember.user)
  games: GameMemberEntity[]
}
@Entity()
export class GameEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  name: string

  @Column({ default: false })
  published: boolean

  @OneToMany(() => GameMemberEntity, gameMember => gameMember.game)
  members: GameMemberEntity[]
}
@Entity()
export class GameMemberEntity extends BaseEntity {
  @ManyToOne(() => UserEntity, user => user.games, { primary: true })
  user: UserEntity

  @ManyToOne(() => GameEntity, game => game.members, { primary: true })
  game: GameEntity

  @Column({ default: false })
  edit: boolean
}

I’m trying use findOne, but members no pass to query parameters.

    const repository = await getRepository(GameEntity)
    const data = await repository.findOne({
      where: { id: 2, members: { user: { id: 5 } } },
      relations: ['members', 'members.user'],
    })

I expected that

...
WHERE "game_entity"."id" = 2 AND "game_member_entity"."userId" = 5;

But is

...
WHERE "game_entity"."id" = 2;

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:6
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
miyicommented, Nov 5, 2020

if you are looking for a GameEntity with id: 2, you already found the object you are looking for, the additional GameEntityMember: { user: id } requirement is redundant.

const repository = await getRepository(GameEntity)
    const data = await repository.findOne({
      where: { id: 2},
      relations: ['members', 'members.user'],
    })

will give you the exact same result as below every time

const repository = await getRepository(GameEntity)
    const data = await repository.findOne({
      where: { id: 2, members: { user: { id: 5 } } },
      relations: ['members', 'members.user'],
    })
3reactions
maximelafariecommented, Apr 7, 2020

Just a question, are you using @nestjsx/crud? Because I think (in my case) it can come from it…

Anyway, I fixed this with:

  async findByToken(token: string): Promise<Users | undefined> {
    return this.repo.createQueryBuilder('user')
    .leftJoinAndSelect(
      'user.userProduits',
      'userProduits')
    .where('userProduits.token = :token', { token })
    .getOne();
  }

I hope it will help you! 🖖

Read more comments on GitHub >

github_iconTop Results From Across the Web

FindOne in ManyToMany relation with a custom field ...
I found a way to get all data from the relation using the createQueryBuilder method. this.companyRepository .createQueryBuilder('company') .
Read more >
Many-to-one / one-to-many relations - typeorm - GitBook
Many-to-one / one-to-many is a relation where A contains multiple instances of B, but B contains only one instance of A. Let's take...
Read more >
NestJS: blog-api: findOne, findAll, create... & relation ...
NestJS: blog-api: findOne, findAll, create... & relation ManyToOne | Blog Project V-20 ; Link to repository: Github: https://github.com/ ...
Read more >
Associations - Sequelize
The A.hasOne(B) association means that a One-To-One relationship exists between A and B , with the foreign key being defined in the target...
Read more >
Database | NestJS - A progressive Node.js framework
Relations # ; One-to-many / Many-to-one, Every row in the primary table has one or more related rows in the foreign table. Use...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found