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
})
)
})()
06.sequelize 查找 find
最新推荐文章于 2022-08-24 11:04:30 发布