TypeORM是一个开源的对象关系映射(ORM)库,用于在Node.js和浏览器中与数据库进行交互。它支持多种数据库系统,包括MySQL、PostgreSQL、SQLite、Microsoft SQL Server等。
在TypeORM中,可以使用getRepository
方法获取实体的存储库(repository),然后使用存储库的方法进行数据库操作。要从列名数组中查找列的where结果,可以使用存储库的find
方法,并在where
条件中指定列名数组。
以下是一个示例代码:
import { Entity, Column, PrimaryGeneratedColumn, createConnection } from "typeorm";
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
age: number;
}
async function findColumnByNames(columnNames: string[]): Promise<User[]> {
const connection = await createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "password",
database: "database",
entities: [User],
synchronize: true,
});
const userRepository = connection.getRepository(User);
const users = await userRepository.find({
where: columnNames.map((columnName) => ({ [columnName]: Not(IsNull()) })),
});
await connection.close();
return users;
}
// 调用示例
const columnNames = ["name", "age"];
findColumnByNames(columnNames)
.then((users) => {
console.log(users);
})
.catch((error) => {
console.error(error);
});
在上述示例中,我们定义了一个User
实体,包含id
、name
和age
三个列。findColumnByNames
函数接受一个列名数组作为参数,并使用getRepository
方法获取User
实体的存储库。然后,我们使用存储库的find
方法,并在where
条件中使用columnNames.map
方法生成列名的查询条件。最后,通过调用findColumnByNames
函数并传入列名数组,可以获取到符合条件的用户列表。
推荐的腾讯云相关产品:腾讯云数据库(TencentDB),提供了多种数据库引擎和存储类型,适用于各种应用场景。您可以通过以下链接了解更多信息:
请注意,以上答案仅供参考,具体的解决方案可能因实际情况而异。
领取专属 10元无门槛券
手把手带您无忧上云