继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【备战春招】第19天 nest typeorm

有梦
关注TA
已关注
手记 82
粉丝 25
获赞 19

课程名称:NestJS 入门到实战 前端必学服务端新趋势


课程章节: 第1章


课程讲师:Brian


课程内容



@Injectable

将类定义为提供者

@InjectRepository() 另一方面是 @Inject() 的扩展,它采用当前传递的实体/存储库并使用一些逻辑来创建新的注入令牌.通常,此逻辑是 Repository 有时会添加 connection.此令牌与从 TypeormModule.forFeature() 为同一实体创建的令牌匹配.(旁注:如果传递的实体是存储库,则令牌只是 带有可选连接(如果不是默认连接).

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository:
    Repository<User>
  ){}
  findAll(){
    return this.userRepository.find()
  }
  find(username: string) {
    return this.userRepository.findOne({where: {username}})
  }
  async create(user: User) {
    const userTmp = await this.userRepository.create(user)
    return this.userRepository.save(userTmp)
  }
  update(id: number, user:Partial<User>) {
    return this.userRepository.update(id, user)
  }
  remove(id:number){
    return this.userRepository.delete(id)
  }
}

relations 表示是否显示 关联数据

async findUserLogs(id: number) {
    const user = await this.findOne(id)
    return this.logsRepository.find({
      where: {
        user
      },
      relations: {
        user: true
      }
    })
  }

http://img3.mukewang.com/63fafc940001d54705540388.jpg

在uservice 里面 可以使用两种方式进行 sql 的查询

findLogsByGroup(id: number) {
   
   // return this.logsRepository
   // .createQueryBuilder('logs')
   // .select('logs.result', 'result')
   // .addSelect('COUNT("logs.result")','count')
   // .leftJoinAndSelect('logs.user','user')
   // .where('user.id = :id',{id})
   // .groupBy('logs.result')
   // .orderBy('result','DESC')
   // .getRawMany()
   return this.logsRepository.query('select logs.result as result,count(logs.result) as count from logs,user where user.id = logs.userId and user.id = 2 group by logs.result')
 }

一种是 typeorm 提供的 链式 sql

一种是 原生的sql


http://img.mukewang.com/63fafcbd0001e20f08680467.jpg









打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP