sequelize操作,5.查询,总数、分页、联表

10 篇文章 0 订阅
查询
const { User, Blog } = require('./model')
// 创建
!(async function() {
  // 查询一个
  const zj = await User.findOne({
    where: {
      userName: 'zj'
    }
  })
  console.log('zj: ', zj.dataValues)

  // 查询列
  const zjInfo = await User.findOne({
    attributes: ['userName', 'nickName']
  })

  console.log('info: ', zjInfo.dataValues)

  // 查询集合
  const zjBlogs = await Blog.findAll({
    where: {
      userId: 1
    },
    order: [
      ['id', 'desc']
    ]
  })
  console.log('zjBlogs: ', zjBlogs.map( blog => blog.dataValues))

  // 分页
  const blogPageList = await Blog.findAll({
    order: [
      ['id', 'desc']
    ],
    limit: 2,
    offset: 2
  })

  console.log('blogPageList: ', blogPageList.map( blog => blog.dataValues))

  // 查询总数
  const blogListAndCount = await Blog.findAndCountAll({
    order: [
      ['id', 'desc']
    ],
    limit: 2,
    offset: 2
  }) 
  console.log('blogListAndCount:',
   blogListAndCount.count, // 总数
   blogListAndCount.rows.map(blog => blog.dataValues) 
   )

   // 联表查询
   const blogListWithUser = await Blog.findAndCountAll({
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: User,
        attributes: ['userName', 'nickName'],
        where: {
          userName: 'zj'
        }
      }
    ]
  })  
  console.log('blogListWithUser: ',
  blogListWithUser.count,
  blogListWithUser.rows.map(blog => {
    const blogVal = blog.dataValues
    blogVal.user = blogVal.user.dataValues
    return blogVal
  })
  )

  // 联表查询2
  const userListWithBlog = await User.findAndCountAll({
    attributes: ['userName', 'nickName'],
    include: [
      {
        model: Blog
      }
    ]
  }) 
  console.log('userListWithBlog: ',
  userListWithBlog.count,
  userListWithBlog.rows.map(user => {
    const userVal = user.dataValues
    userVal.blogs = userVal.blogs.map(blog => blog.dataValues)
    return userVal
  })
  )
})()

sequelize 1.连接数据库
sequelize 2.创建模型
sequelize 3. 根据模型创建数据库
sequelize 操作 4.新增

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值