【问题标题】:How to get result from multiple tables with `leftJoin` in typeorm?如何在 typeorm 中使用“leftJoin”从多个表中获取结果?
【发布时间】:2021-02-21 09:22:07
【问题描述】:

我有三张桌子:

1.视图表:

id   type    created_at    status  action_id
-----------------------------------------
1    page_1  2020-01-01    1       2

2。项目表:

id   view_id   image       action_id
-------------------------------------
1    1         thumb.png   1

3.动作表:

id    message
------------------------------------
1     this is a test
2     this an action for header view

我期待的结果是:

{
    "status": 1,
    "action": {
         "message": "this an action for header view"
     },
     "items": [
         {
           "id": 1,
           "description": "Comments",
           "image": "comment.png",
           "status": 1,
           "action": {
                 message: "this is test"
              }
          }
      ]
}

另外,我已经通过one-to-oneone-to-many 装饰器创建了所有具有所需关系的Entities。 那么如何在ViewRepository 中使用this.createQueryBuilder('view') 获得结果?

【问题讨论】:

    标签: mysql node.js mariadb typeorm


    【解决方案1】:

    我现在可以通过这种方式获取所有必需的列:

    @EntityRepository(View)
    export class ViewRepository extends Repository<View> {
        async getView() {
            return await this.createQueryBuilder('view')
                .leftJoinAndSelect("view.action", "action")
                .leftJoinAndSelect("view.items", "item")
                .leftJoinAndSelect("item.action", "itemAction")
                .select([
                    "view.type",
                    "action.message",
                    'itemAction.message',           
                    'item.image',
                    'item.id'
                ])
                .getOne()
        }
    }
    

    【讨论】:

      【解决方案2】:
      this.viewRepository.createQueryBuilder('view')
        .leftJoin('view.items', 'item') // 'view.items' will work if you describe 'items' property in ViewEntity as a relation
        .leftJoin('view.action', 'viewAction')
        .leftJoin('item.action', 'itemAction') // the same as above, but for ItemEntity
        .select(['view.status', 'viewAction.message', 'item.id', 'item.description', 'item.image', 'item.status', 'itemAction.message']) // probably you needed to select ids from rest tables too, for correct joining 
        .where(<here is your 'where' condition>)
        .getOne() // or .getMany() if you wanna to get multiple results
      

      更新:不确定它是否可以在存储库中工作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-08
        • 2017-11-12
        • 2021-04-15
        • 2013-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多