亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【備戰春招】第19天 nest typeorm

標簽:
Node.js

课程名称: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
      }
    })
  }

https://img1.sycdn.imooc.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


https://img1.sycdn.imooc.com//63fafcbd0001e20f08680467.jpg









點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
27
獲贊與收藏
19

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消