【问题标题】:How to get only column name from relation如何从关系中仅获取列名
【发布时间】:2020-08-26 19:26:40
【问题描述】:

如何加入列,当我启动我的函数时,他只返回列名而不是entity_columnName

我正在使用 TypeORM,我试试这个;

const data = this.conn.getRepository(User).createQueryBuilder('user');
data.leftJoinAndSelect('user.orders', 'orders');
data.getRawMany();

但是返回我:

firstName: ...
lastName: ...
age: ...
order_name: ...
order_price: ...

代替:

firstName: ...
lastName: ...
age: ...
name: ...
price: ...

谁能告诉我这是怎么做的?感谢您的帮助

【问题讨论】:

    标签: javascript typescript nestjs


    【解决方案1】:

    您的用户和订单实体是如何定义的?

    如果您使用 eager: true 选项定义关系(例如 OneToMany),则 TypeORM 将在您使用存储库 *find 方法查询时自动包含相关实体。当您使用 QueryBuilder 时它不会这样做,您必须在其中添加它们,例如 leftJoinAndSelect()(就像您所做的那样)。

    具有 OneToMany 行项目的 Invoice 实体示例:

      @OneToMany(
        () => InvoiceLineItem,
        (item: InvoiceLineItem) => item.invoice,
        { eager: true }
      )
      items: InvoiceLineItem[]
    

    例如,如果我当时是 find()findMany() 发票,那么相关对象 items 也将包括在内,因为 eager: true

    这种行为可能会很好地转化为您的用户和订单情况。

    在使用查询生成器时,还要注意getMany()getRawMany() 之间的区别。

    如果你使用getMany(),那么 TypeORM 会自动返回实体(例如,你会得到一个User 的实例,其属性为orders,它是一个Order 实例的数组)。属性名称将是正确的。

    由于您在问题中添加了 NestJS 标记,因此还要了解序列化: https://docs.nestjs.com/techniques/serialization

    NestJS 附带了一个内置的ClassSerializerInterceptor,您可能会发现它很有用。

    在您的控制器中,您可以装饰类或其任何方法,例如

    @UseInterceptors(ClassSerializerInterceptor)
    

    这会将响应转换为 JSON,并将使用 class-transformer 装饰器指定的规则应用于实体/DTO 类。

    如果您要使用此拦截器,则发送给客户端的响应将具有您想要的属性名称。

    如果您真的想要修改客户端返回的响应,您也可以考虑编写自己的拦截器。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2020-04-04
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多