【问题标题】:Trying to Order By in Sequelize but get error "Unable to find a valid association for model"尝试在 Sequelize 中排序,但出现错误“无法找到模型的有效关联”
【发布时间】:2021-10-25 18:19:17
【问题描述】:

我正在尝试在 Sequelize 中订购包含关联(多对多)的 findByPk 结果,但我遇到了一些问题。我不断收到错误:

错误:无法找到模型“项目”的有效关联

查询:

        Guest.findByPk(id,
            {
                include: { model: db.Item, as: 'items' },
                order: [
                    [ { model: db.sequelize.models.Item, as: 'items' }, 'dexId', 'ASC' ]
                ]
            })
            .then(data => {
                res.status(200).json({ items: data.items});
            })
            .catch(err => {
                const error = new createError(500, "Error retrieving Guest with id=" + id);
                return next(error);
            });

物品型号:

'use strict';
const {
    Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
    class Item extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            Item.belongsToMany(models.Guest, {
                //through: 'GuestItems',
                through: {
                    model: 'GuestItems',
                    unique: false
                },
                constraints: false,
                as: 'guests',
                foreignKey: 'itemId',
                otherKey: 'guestId'
            });
            Item.belongsToMany(models.User, {
                //through: 'UserItems',
                through: {
                    model: 'UserItems',
                    unique: false
                },
                constraints: false,
                as: 'users',
                foreignKey: 'itemId',
                otherKey: 'userId'
            });
        }
    }

    Item.init({
        dexId: {
            allowNull: true,
            type: DataTypes.INTEGER,
            defaultValue: null
        },
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        description: DataTypes.STRING,
        filename: DataTypes.STRING,
    }, {
        sequelize,
        modelName: 'Item',
        paranoid: true
    });
    return Item;
};

客座模特

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Guest extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      Guest.belongsToMany(models.Item, {
        through: 'GuestItems',
        as: 'items',
        foreignKey: 'guestId',
        otherKey: 'itemId'
      });
    }
  }
  Guest.init({
    id: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    token: DataTypes.STRING,
    role: {
      type: DataTypes.ENUM,
      values: ["guest"],
      defaultValue: "guest"
    },
    lastIPAddress: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Guest',
    associations: true
  });
  return Guest;
};

我知道事实 db.sequelize.models.Item 存在,我也尝试过调用 db.Item (同样存在并在其他地方使用) - 两者都不起作用。 我也试过了

  [ db.sequelize.models.Item, 'dexId', 'ASC' ]

而不是 { as 'items' } 位,但我仍然收到该错误。

我正在使用最新版本的 Sequelize 和 Postgresql

【问题讨论】:

    标签: javascript node.js postgresql sequelize.js


    【解决方案1】:
    Guest.findByPk(id, {
            include: {model: db.Item, as: 'items', required: true},
            order: [[sequelize.literal('"items"."dexId"'), 'ASC']] 
    })
        .then((data) => {
                res.status(200).json({items: data.items});
        })
        .catch((err) => {
                    return next(error);
        });
    

    【讨论】:

    • TypeError: 无法读取未定义的属性“类型”
    • 更新代码,请尝试required: true
    • 同样的错误,TypeError: Cannot read property 'type' of undefined
    • 与github分享小项目
    • order: [[sequelize.literal('"items"."dexId"'), 'ASC']] 有效,但前提是两个表中都有条目 - 我怎样才能使它工作在空表的情况下? “TypeError: Cannot read property 'items' of null”是表为空时发生的情况
    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 2016-08-22
    • 2022-07-22
    • 2014-03-17
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多