首页 > 解决方案 > sequelize - 添加外键后内部连接出错

问题描述

我有这两个模型:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('services_prices', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true
    },
    service_id: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'services',
        key: 'id'
      }
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false
    },
    limit: {
      type: DataTypes.INTEGER(11),
      allowNull: true
    },
    price: {
      type: DataTypes.INTEGER(11),
      allowNull: true
    }
  });
};

这是此模型的父级:(services_user_prices 可以覆盖 services_prices)

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('services_user_prices', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER(11),
      allowNull: true
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false
    },
    currency: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    is_active: {
      type: DataTypes.INTEGER(1),
      allowNull: true,
      defaultValue: '0'
    },
    is_trial: {
      type: DataTypes.INTEGER(1),
      allowNull: true,
      defaultValue: '0'
    },
    start_date: {
      type: DataTypes.DATE,
      allowNull: false
    },
    end_date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    price: {
      type: DataTypes.INTEGER(11),
      allowNull: true
    },

    bundle_price_id: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'services_prices',
        key: 'id'
      }
    }
  });
};

尝试加入他们时出现错误:

EagerLoadingError:services_prices 未与 services_user_prices 关联!

 const result= await db.services_user_prices.findOne({
                where: { is_active: 1, user_id: 123 }, include:[{db.services_prices}]
            });

在 db services_user_prices 中有 services_prices 表的外键我做错了什么?

标签: node.jssequelize.js

解决方案


好吧,如果您使用的是 sequelize,那么您需要更新您的模型,因为

默认情况下,sequelize 将寻找以模型名称开头的外键,例如

您已将bundle_price_id.services_prices

您需要将列名更改为,services_price_id然后它将得到修复。

或者如果你想使用bundle_price_id你需要在你的模型关系中定义它。

Model.belongsTo(models.ModelName, { foreignKey: 'your_key'} )

如果您需要问其他任何问题,请随时提出。


推荐阅读