typeOrm 操作
使用
引入
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
export class PostsService {
constructor(
@InjectRepository(PostsEntity)
private readonly postsRepository: Repository<PostsEntity>,
) {
}
}
普通查询 (findOne,find)
const doc = await this.postsRepository.findOne({ where: { title } });
const existPost = await this.postsRepository.findOne({where: { id: blogId },});
const allViewedPhotos = await this.postsRepository.find({where: { id: blogId }});
带有关联的查询
const doc = await this.postsRepository.findOne({ where: { title }, relations: ['user'] });
const existPost = await this.postsRepository.findOne({where: { id: blogId }, relations: ['user']});
const allViewedPhotos = await this.postsRepository.find({where: { id: blogId }, relations: ['user']});
使用createQueryBuilder查询
const allViewedPhotos = await this.postsRepository
.createQueryBuilder('posts')
.where('posts.title LIKE :title')
.setParameters({ title: `%${data.title}%` })
.andWhere('posts.author LIKE :author')
.setParameters({ author: `%${data.author}%` })
.getMany();