如何在sequelize中创建限制查询?

问题描述 投票:0回答:1

我正在尝试在查询中创建一个限制,该限制应该如下所示:

 /api/hotels?featured=1&limit=2

当我尝试通过邮递员执行时,我收到此消息:

“message”:“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以了解在第 1 行 ''2'' 附近使用的正确语法”,

我可以看到服务器返回这个:

执行(默认):SELECT id、名称、类型、城市、地址、距离、 照片、标题、描述、评级、房间、最便宜的价格、精选、 createAt、updateAt FROM 酒店 AS 酒店 WHERE Hotels.featured = '1' AND Hotels.limit = '2' LIMIT '2';

我的控制器看起来像这样:


//GET ALL
export const getHotels = async (req, res, next) => {
  try {
    const { min, max, ...others } = req.query;

    const hotels = await Hotel.findAll({
      where: {
        ...others,
      },
      limit: req.query.limit,
    });

    res.status(200).json(hotels);
  } catch (err) {
    next(err);
  }
};

我的模型看起来像这样:

const Hotel = (sequelize, Sequelize) => {
  const Hotel = sequelize.define("hotels", {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    type: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    city: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    address: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    distance: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    photos: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    title: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    desc: {
      type: DataTypes.TEXT,
      allowNull: false,
    },
    rating: {
      type: DataTypes.INTEGER,
      min: 0,
      max: 4,
    },
    rooms: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    cheapestPrice: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    featured: {
      type: DataTypes.BOOLEAN,
      default: false,
    },
  });
  return Hotel;
};
mysql reactjs node.js sequelize.js
1个回答
0
投票

限制应该是数字而不是字符串;你可以尝试下面的方法吗 请注意,此代码未经测试

Number(req.query.limit)

export const getHotels = async (req, res, next) => {
  try {
    const { min, max,limit, ...others } = req.query;

    const hotels = await Hotel.findAll({
      where: {
        ...others,
      },
      limit: Number(limit),
    });

    res.status(200).json(hotels);
  } catch (err) {
    next(err);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.