灏天阁

Node/Koa2[12]: sequelize查询数据

· Yin灏

src/select.js

const { Blog, User } = require("./model");
!(async function () {
  // 查询一条记录
  const zhangsan = await User.findOne({
    where: {
      userName: "zhangsan",
    },
  });
  console.log(zhangsan.dataValues);

  // 查询特定的列
  const zhangsanName = await User.findOne({
    attributes: ["userName", "nickName"],
    where: {
      userName: "zhangsan",
    },
  });
  console.log(zhangsanName.dataValues);
  // 查询一个列表
  const zhangsanBlogList = await Blog.findAll({
    where: {
      userId: 1,
    },
    order: [["id", "desc"]],
  });
  console.log(zhangsanBlogList.map((blog) => blog.dataValues));
  // 分页查询
  const blogPageList = await Blog.findAll({
    limit: 2,
    offset: 0,
    order: [["id", "desc"]],
  });
  console.log(blogPageList.map((blog) => blog.dataValues));
  // 查询总数
  const blogListAndCount = await Blog.findAndCountAll({
    limit: 2,
    offset: 0,
    order: [["id", "desc"]],
  });
  // blogListAndCount.count 所有的总数,不管是否分页
  console.log(blogListAndCount.count);
  console.log(blogListAndCount.rows.map((blog) => blog.dataValues));
})();

- Book Lists -