要使用TypeORM按目标查询,可以按照以下步骤进行操作:
npm install typeorm --save
User
实体类。可以使用装饰器@Entity()
定义实体类,并使用@Column()
装饰器定义实体类的属性。例如:import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
age: number;
}
import { createConnection } from 'typeorm';
createConnection({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'database',
entities: [
User,
],
synchronize: true,
logging: true,
}).then(connection => {
// 连接已创建
}).catch(error => {
console.log('连接错误:', error);
});
import { getManager } from 'typeorm';
async function getUsers() {
const entityManager = getManager();
const users = await entityManager.find(User, { where: { age: MoreThan(18) } });
console.log(users);
}
getUsers();
在上面的示例中,getUsers()
函数使用getManager()
方法获取实体管理器,然后使用find()
方法执行查询。find()
方法接受两个参数:要查询的实体类和查询选项。在查询选项中,可以使用TypeORM提供的各种查询操作符,例如MoreThan
。
这是一个简单的使用TypeORM按目标查询的示例。根据具体的需求,可以使用不同的查询选项和操作符来构建更复杂的查询。