当前位置: 首页 > 知识库问答 >
问题:

node.js - nestJS中TypeORM如何根据请求参数动态查询表?

巫经义
2023-08-27

假设有两个数据库,其中date数据库的表每天一张,表名根据日期创建:20230801,20230802...

要根据请求的接口参数日期范围,动态去连接表查询该如何操作呢?

imports: [        TypeOrmModule.forRoot({            name: 'db1Connection', // 指定连接名称            type: 'mysql',            host: 'localhost',            port: 3306,            username: 'root',            password: '123456',            database: 'date',            entities: [Date],            autoLoadEntities:true, // 自动加载实体            synchronize: true,        }),        TypeOrmModule.forRoot({            name: 'db2Connection', // 指定连接名称            type: 'mysql',            host: 'localhost',            port: 3306,            username: 'root',            password: '123456',            database: 'test',            entities: [Goods],            autoLoadEntities:true, // 自动加载实体            synchronize: true,        }),        TypeOrmModule.forFeature([Date], 'db1Connection'),        TypeOrmModule.forFeature([Goods], 'db2Connection')    ],

实体指定表名查询是OK的。

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';@Entity('good')export class Goods {  @PrimaryGeneratedColumn()  id: number;  @Column({ length: 128 })  name: string;  @Column()  desc: string;  @Column()  price: number;  @Column()  sum: number;}
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';@Entity()export class Date {  @PrimaryGeneratedColumn()  id: number;  @Column({ length: 128 })  title: string;  @Column()  content: string;  @Column()  userId: number;}

上面的实体没有指定表名,每次查询自动创建了一个 date 表 。。
目前数据库有如下表:
20230801
20230802
20230803

我想的是根据查询的参数去动态查询这些表,可能是一张也可能是多张表

import { Injectable, Inject } from '@nestjs/common';import { Repository, EntityManager } from 'typeorm';import { InjectRepository, InjectEntityManager, } from '@nestjs/typeorm';import { Date } from 'src/entitys/date.entity';import { Goods } from 'src/entitys/goods.entity';@Injectable()export class DateService {  constructor(    @InjectRepository(Date, 'db1Connection') private dateRepository: Repository<Date>,    @InjectRepository(Goods, 'db2Connection') private goodsRepository: Repository<Goods>,  ) {}  async findByDate() {  }  async findAll() {  }  async findGoods() {    return this.goodsRepository.find();  }}

共有1个答案

庾和昶
2023-08-27

用注解定义实体,是程序加载的时候就定义了,@Entity() 不传参数相当于用class 名作为表名。

实体可以分离定义:

import {EntitySchema} from "typeorm";export const CategoryEntity = new EntitySchema({    name: "category",    columns: {        id: {            type: Number,            primary: true,            generated: true        },        name: {            type: String        }    }});

然后再使用:

// 请求数据const categoryRepository = getRepository<Category>(CategoryEntity);const category = await categoryRepository.findOne(1); // category is properly typed!// 插入一条新category到数据库const categoryDTO = {  // 注意id是自动生成的,请参考上面的架构定义。  name: 'new category',};const newCategory = await categoryRepository.save(categoryDTO);

参考:typeorm

 类似资料:
  • 假设我们有两个服务,A和B。服务A有一个函数执行以下操作: 验证数据 现在,让我们假设以下步骤之一,步骤3或4失败。由于服务B对数据库进行了更改,这些更改仍然存在。 在这种情况下,有没有办法回滚数据库?我曾考虑过数据库事务,但在nest js中找不到任何方法来实现这一点,尽管TypeOrm支持它,但nest看起来并不自然。如果不是的话,我现在被服务B所做的更改“卡住”了,但是如果没有服务B所做的更

  • 问题内容: 我有一个HTTP客户端(目前)的Node.js应用程序。所以我在做: 这似乎是完成此任务的一种好方法。但是,我有些沮丧,我必须执行此步骤。这应该由一个公共库封装,但是我还没有看到它存在于node的库中,而且我不确定哪个标准的npm包可以完成它。有没有一种合理使用的更好的方法? url.format方法节省了构建自己的URL的工作。但理想情况下,请求的级别也应高于此级别。 问题答案: 检

  • 自1.14.0开始,zuul网关支持动态修改请求参数。即在网关修改客户端传递过来的参数,然后发送到微服务端。 客户端参数{"name": "jim"} --> zuul中修改为{"name": "Lucy"} --> 微服务端将收到{"name": "Lucy"} 使用场景:客户端请求参数经过加密,在网关解密后,再次发送明文参数给微服务端 如何使用 在网关springboot启动函数中添加如下代

  • 本文向大家介绍Dapper.NET 用动态参数查询,包括了Dapper.NET 用动态参数查询的使用技巧和注意事项,需要的朋友参考一下 示例            

  • 问题内容: 我有一个存储在列表中的关键字列表。 要从表中获取记录,请使用以下查询: 您可能已经注意到,我的查询容易受到sql注入的攻击,因此我想通过SqlCommand()使用参数。我已经尝试了以下方法,但仍然无法正常工作: 我在哪里犯错,或者应该怎么做? 问题答案: 您在这里做错了几件事: 您为所有参数赋予相同的名称。那行不通。参数需要唯一的名称。 您为每个项目创建一个新的SqlCommand。

  • 所以我正在用NestJs和mongodb进行一个项目。早些时候,我们使用express和mongoose,为了在数组列中查找结果,我们使用了如下方法: 现在,当我们使用TypeORM迁移到新的Nest后端时,我们使用的是: 但这不起作用。奇怪的是,除此之外,我们在mongoose中使用的所有查询都能正常工作。我试着用NestJS处理mongoose,这确实有效,所以函数参数或任何东西都没有问题。