【问题标题】:Typescipt: how to access class-contants from typeorm getManager.query()打字稿:如何从 typeorm getManager.query() 访问类常量
【发布时间】:2020-07-01 15:32:34
【问题描述】:

我对 typeORM/Typescript 世界比较陌生。我有一个服务类来提供如下资源:

import { Injectable} from '@nestjs/common';
import { getManager } from 'typeorm';

class MyServiceClass {

//static readonly sqlStr = `SELECT MAINTABLE.* WITH LEFT OUTER JOIN WITH TWO MORE TABLES `;

async findAll(limit?: number) {
    const mgr = getManager();
    const retRows = await mgr.query(
      `
      SELECT MAINTABLE.* WITH LEFT OUTER JOIN WITH TWO MORE TABLES

          ${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
      `,
    );
    return retRows;
  }

async findOne(id: number) {
    const mgr = getManager();
    const retRow = await mgr.query(
      `
      SELECT MAINTABLE.* WITH LEFT OUTER JOIN WITH TWO MORE TABLES

        ${id ? ` WHERE MAINTABLE.MAIN_ID = ${id}` : ''}
      `,
    );
    return retRow;
  }

}

我想从每个函数中删除 sql 语句,但保留过滤逻辑。相反,我想在 mgr.query() 函数中使用 MyServiceClass.sqlStr 。如果有人指出我该怎么做,那就太好了。

【问题讨论】:

    标签: typescript nestjs typeorm


    【解决方案1】:

    您应该使用 typeorm 模块中的存储库工具:

    async findAll(limit?: number) {
        const entities = await this.entityRepository.findAll(
          { where: { id: 1 } }, relations: ['someRelation'], sort: {id: 'DESC'},
          /* you can create very advanced requests */
        );
    
        return entities;
      }
    

    或使用查询生成器:

    async findAll(limit?: number) {
        const rows = await this.entityRepository
           .createQueryBuilder('Entity')
           .leftJoinAndSelect('Entity.relation', 'relation')
           .where('relation.id = :id', {id: 1})
           /* any query condition here */
           .getMany() // or .getSql() or whatever you want
    
        return rows;
      }
    

    详细了解如何设置 typeorm 存储库here

    更多关于查找选项here

    查询生成器文档here

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 2018-09-06
      • 2021-03-20
      • 2021-06-17
      • 1970-01-01
      • 2017-06-20
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多