【问题标题】:Typeorm - Find entries by ManyToMany relationTypeorm - 按多对多关系查找条目
【发布时间】:2019-11-11 00:46:50
【问题描述】:

我正在将 Nestjs 与 Typeorm 和 Mysql 一起使用,但我想不出一种按多对多关系过滤条目的好方法。

我有这两个实体:

集团实体:

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

标记实体

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

并且想搜索所有带有特定文本标签的组。

即。所有具有tag.tag“sport”的组

试过这个代码:

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

return super.findAll(args);

但它似乎不起作用..

任何帮助都会很棒!

【问题讨论】:

    标签: sql nestjs typeorm


    【解决方案1】:
    return find({
      where: {
        tags: {
          tag: Like(`%sport%`),
        },
      },
      relations: ['tags'],
    });
    

    几乎,typeorm 从如下关系中接受 ObjectLiteral 或 keyof typeof 标签:

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

    这并不完全是,但这是一般要点。如果keyof T 是一个关系,那么any 无论如何都会被keyof relation 替换。

    这是 findConditions https://github.com/typeorm/typeorm/blob/master/src/find-options/FindConditions.ts 的完整类型

    【讨论】:

    • 非常感谢,不幸的是,现在我收到此错误:QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'Group.groupsId' in 'where clause 我猜它与我构建实体的方式有关?我在标签实体中没有任何组引用(有意)。
    • 我猜你还没有将你的数据库与你的实体架构同步
    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2020-09-02
    • 2020-06-29
    • 2020-09-01
    • 2020-12-03
    • 2020-09-27
    • 2021-12-26
    • 2020-10-10
    相关资源
    最近更新 更多