简体   繁体   中英

Typeorm - Find entries by ManyToMany relation

I am using Nestjs with Typeorm and Mysql, and I can't figure out a good way to filter entries by their many to many relation.

I have these 2 entities:

Group Entity:

@Entity({ name: 'groups' })
export class Group {
    @ManyToMany(() => Tag, { eager: true })
    @JoinTable()
    tags: Tag[];
}

Tag Entity

@Entity({ name: 'tags' })
export class Tag {
    @Column()
    @Index({ unique: true })
    tag?: string;
}

And would like to search all groups that have a tag with a specific text.

ie. all groups that have the tag.tag "sport"

Tried this code:

const args = {
    where: [
        {
            'tags': In([Like(`%sport%`)]),
        }
    ],
    relations: ['tags'], // TAGS
    take: filter.take,
    skip: filter.skip,
    order: filter.order
};

return super.findAll(args);

but it doesn't seem to work..

any help would be great!

return find({
  where: {
    tags: {
      tag: Like(`%sport%`),
    },
  },
  relations: ['tags'],
});

Almost, typeorm accepts an ObjectLiteral or keyof typeof Tags from relations like so:

FindConditions<T>: {
  where: {
    [s: keyof typeof T]: any,
  },
}

That's not quite it but that's the general gist. And if the keyof T is a relation then any is replaced with keyof relation pretty much anyway.

This is the full type for findConditions https://github.com/typeorm/typeorm/blob/master/src/find-options/FindConditions.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM