node.js - 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 表的外键我做错了什么?
解决方案
好吧,如果您使用的是 sequelize,那么您需要更新您的模型,因为
默认情况下,sequelize 将寻找以模型名称开头的外键,例如
您已将bundle_price_id
.services_prices
您需要将列名更改为,services_price_id
然后它将得到修复。
或者如果你想使用bundle_price_id
你需要在你的模型关系中定义它。
Model.belongsTo(models.ModelName, { foreignKey: 'your_key'} )
如果您需要问其他任何问题,请随时提出。
推荐阅读
- c# - 如何将路由名称与路由参数结合起来
- java - Java快速排序 - 是否可以在不使用比较器的情况下比较对象?
- css - 我的“grunt watch”正在运行,但它没有应用从 SCSS 到 CSS 的更改
- curl - curl 请求和 globbing 括号
- android-ndk - 哪个(最新)llvm 版本是 Android NDK 的正确版本?
- python-3.x - 删除 Anaconda3 后,我仍然在 PowerShell 中收到这些错误
- github - 尝试从 github 导入代码到故障,但错误消息已显示
- r - 我可以在 Shiny plot_ly 中“配对”轨迹,以便在单击图例时出现/消失两条轨迹吗?
- python - 如何在 Django ORM 中使用条件预取或子查询深度嵌套的对象
- r - 按子字符串对向量进行排序