Gx
主页
  • 甘特图开发
  • 前端考核
  • js
  • DOCKER 初始化
  • docker 镜像使用
  • docker 镜像定制
  • nestjs 安装
  • 连接数据库
  • typeOrm 操作
  • 任务调度
  • typeorm 一对多,多对一 多对多 一对一 对应实体之间的关系
  • sql 练习
  • 文件相关
  • ts学习
  • 面试题
  • rust
  • 入门
  • 基础知识
  • 性能公式
  • 线性回归
  • 基础语法
  • 数据类型
  • 复合类型
  • rust 控制流 匹配模式
  • ❤️ 父子传参
  • 🔔 Git的提交规则
主页
  • 甘特图开发
  • 前端考核
  • js
  • DOCKER 初始化
  • docker 镜像使用
  • docker 镜像定制
  • nestjs 安装
  • 连接数据库
  • typeOrm 操作
  • 任务调度
  • typeorm 一对多,多对一 多对多 一对一 对应实体之间的关系
  • sql 练习
  • 文件相关
  • ts学习
  • 面试题
  • rust
  • 入门
  • 基础知识
  • 性能公式
  • 线性回归
  • 基础语法
  • 数据类型
  • 复合类型
  • rust 控制流 匹配模式
  • ❤️ 父子传参
  • 🔔 Git的提交规则
  • typeOrm 操作

typeOrm 操作

使用

引入

// 引入依赖 以及类型
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
        
// 声明类型 并且使用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查询

/* getOne 获取单个 getMany 获取多个 实体 */
/* getRawOne    getRawMany  非实体 */
/*LIKE 模糊匹配*/
    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();


最近更新: 2024/6/18 05:59
Contributors: G_xing