【问题标题】:TypeORM - Many-to-Many where clause on join tableTypeORM - 连接表上的多对多 where 子句
【发布时间】:2018-05-14 09:45:49
【问题描述】:

我正在使用 Typeorm@0.2.5 和 MySql 驱动程序。
我有一个实体MyEntity,它与另一个实体RelEntity 具有多对多关系。因此,Typeorm 会生成 PK 的数据透视表来创建关系。

我的问题来自需要使用 RelEntity.prop = mySearchKey 的 where 子句查找所有 MyEntity

我不确定这是因为我遗漏了一些文档,还是因为我没有完全理解如何使用 Typeorm 来构造这个查询。

我相信我的 SQL 语句看起来像这样:

SELECT m.* FROM my_entity_table m 
LEFT JOIN my_rel_pivot_table mrp ON mrp.my_entity_id = m.id 
LEFT JOIN rel_entity_table r ON r.id = mrp.rel_entity_id
WHERE r.id = {MY_VALUE_HERE}

但是,我不太确定如何将其转换为 Typeorm 查询。

我试过了:

this.entityRepo.find({
    where: {
        rel: myValue
    }
});

我也试过了:

this.entityRepo.find({
    where: {
        rel: { id: myValue}
    }
});

但是,我收到以下错误:
Unknown column 'MyEntity.myEntityId' in 'where clause'

以前有没有人遇到过这个问题,或者知道如何解决这个问题?

【问题讨论】:

    标签: typeorm


    【解决方案1】:

    在我的文章和类别之间(多对多),这对我有用。

    要获取来自特定类别的我的文章

      this
      .entityRepo
      .createQueryBuilder('article')
      .innerJoin(
           'article.categories', 
           'category', 
           'category.id = :categoryId', 
           { categoryId: XXX }
      ).getMany();
    

    XXX是具体分类的id。

    希望对你有所帮助。

    【讨论】:

    • 但是如何在 XXX 字段中输入另一个表中的列?
    【解决方案2】:

    在 GitHub 上寻求帮助后,以下问题的答案是使用 QueryBuilder API。

    可以这样做:

    const myEntities = await this.entityRepo.createQueryBuilder("entity")
        .leftJoin("relEntity", "relEntity.id = :myId", {myId: myValue})
        .getMany()
    

    非常感谢 https://github.com/pleerock 帮助我解决这个问题。

    【讨论】:

    • 有没有办法在当前版本的 TypeORM 中使用 repo.find({where: {}, Relations: []}) 语法来做到这一点?
    • 很遗憾没有,为此有一个公开的 PR。我对此很期待。 (github.com/typeorm/typeorm/issues/2707)
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2023-03-08
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多