Typeorm find with sub relations is not working

1.7k Views Asked by At

I am not able to find rows when searching with sub relations. I tried with and without promise and yet still no luck.

Example entities:

@Entity('email')
export class Email extends BaseEntity {
    @Column({ nullable: false, unique: true })
    email: string;

    @Column({ default: false })
    verified: boolean;

    @ManyToOne(type => User, user => user.emails)
    user: Promise<User>;
}

@Entity('users')
export class User extends BaseEntity {
    @Column({ nullable: false })
    name: string;

    @OneToMany(type => Phone, phone => phone.user)
    emails: Promise<Email[]>;
}

If I use the following:

// user will remain null
const user = await this.userRepo.findOne({
  where: [
    {
      emails: [
        {
           email: '[email protected]'
        }
      ],
  ],
}
// email will also remain null
const email = await this.emailRepo.findOne({
  where: [
    {
      user: {
         name: 'test'
      },
  ],
}

Do anyone know how to solve this? I think it's a bug.

1

There are 1 best solutions below

0
spike 王建 On

find/findOne doesn't allow filtering by nested relation properties. Go for QueryBuilder instead with something like

const x = await repo.createQueryBuilder("email")
    .innerJoinAndSelect("email.users", "user")
    .where("user.name = :name", { name })
    .getOne()

Check here for a similar question.