【问题标题】:How do I sort records from Sequelize?如何对 Sequelize 中的记录进行排序?
【发布时间】:2021-04-04 03:13:57
【问题描述】:

我有以下带有Sequelize 数据查询的API。

这工作正常,但我需要在模型 BuyerAddressBooks 中按“id”的递减顺序对记录进行排序。所以我使用了“订单”,但它对输出没有任何影响。它总是按增量顺序排列。我怎么能修改这个?我是 Sequelize 的新手。

{ model: BuyerAddressBooks, attributes: { exclude: commonExcludes },  order: [['id', 'DESC']] },

这是我的 API 代码:

export const PG_getUserDetails = createContract("Any name as of now")  //PG_BuyerProfile#get
  .params("userId")
  .schema({
    userId: V.number(),
  })
  .fn(async (userId) => {
    const user = await User.findByPk(userId, {
      attributes: { exclude: commonExcludes },
      include: [
        { model: PG_UserDetails, attributes: { exclude: commonExcludes } },
        {
          model: BuyerProfile,
          attributes: { exclude: commonExcludes },
          include: {
            model: PhoneNumbers,
            attributes: ["id", "number", "mobileVerified"],
          },
        },
        { model: BuyerAddressBooks, attributes: { exclude: commonExcludes },  order: [['id', 'DESC']] },
      ],      
    }).then(toPlain);
    if (!user) {
      throw new LogError("Profile not found", 400);
    }
    const { buyerProfile, buyerAddressBooks, phoneNumbers } = user;
    const email = R.pathOr(user, ["userDetail", "email"], null);
    return { email, ...buyerProfile, buyerAddressBooks, phoneNumbers };
  })
  .express({
    method: "get",
    path: "/buyer/pg_profile",
    auth: true,
    async handler(req, res) {
      // @ts-ignore
      const user = req.user;
      console.log(`From console : ${user.id}`);
      res.json(await PG_getUserDetails(+user.id));
    },
  }); 

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    include 选项没有 order 属性。您可以尝试在 User 模型的选项中指定 order,如下所示:

    await User.findByPk(userId, {
          attributes: { exclude: commonExcludes },
          order: [['BuyerAddressBooks', 'id', 'DESC']],
          ...
    

    【讨论】:

    • 谢谢。奇怪的是编译的时候连错误信息都没有。
    • 错误可能与现有选项有关。我想 Sequelize 不会检查选项是否有额外的道具
    • 这也是我目前发现的。
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 2016-07-09
    • 1970-01-01
    • 2019-08-04
    • 2016-03-02
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多