06.sequelize 查找 find

const { Blog, User} = require('./model')

!(async () => {
  // // 查询一条记录
  // const zhangsan = await User.findOne({
  //   where: {
  //     userName: 'zhangsan'
  //   }
  // })
  // // console.log('zhangsan', zhangsan.dataValues)
  //
  // // 查询特定的列
  // const zhangsanName = await User.findOne({
  //   attributes: ['userName', 'nickName'],
  //   where: {
  //     userName: 'zhangsan'
  //   }
  // })
  // // console.log('zhangsanName: ', zhangsanName.dataValues)
  //
  // // 查询一个列表
  // const zhangsanBlogList = await Blog.findAll({
  //   where: {
  //     userId: 1
  //   },
  //   order: [
  //     ['id', 'desc']
  //   ]
  // })
  //
  // // console.log('zhangsanBlogList: ', zhangsanBlogList.map(blog => blog.dataValues))
  //
  // // 分页查询
  // const blogPageList = await Blog.findAll({
  //   limit: 2,  // 限制本次查询 2条
  //   offset: 2,  // 跳过多少条
  //   order: [   // 正序还是倒序
  //     ['id', 'desc']
  //   ]
  // })
  //
  // // console.log(blogPageList.map(blog => blog.dataValues))
  //
  // // 查询总数
  // const blogListAndCount = await Blog.findAndCountAll({
  //   limit: 2,
  //   offset: 2,
  //   order: [
  //     ['id', 'desc']
  //   ]
  // })
  // console.log(
  //   blogListAndCount.count,  // 总数
  //   blogListAndCount.rows.map(blog => blog.dataValues)
  // )

  // 连表查询1 依赖外键的设置
  const blogListWithUser = await Blog.findAndCountAll({
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: User,
        attributes:['userName', 'nickName'],
        where: {
          userName: 'zhangsan'
        }
      }
    ]
  })
  console.log(
    'blogListWithUser',
    blogListWithUser.count,
    blogListWithUser.rows.map(blog => {
      const blogVal = blog.dataValues
      blogVal.user = blogVal.user.dataValues
      return blogVal
    })
  )

})()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值