我有这两个型号:
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中有service_prices表的外键我做错了什么?
作为上述答案的补充,您需要在关联上添加as:
标识符,如下所示:
Model.belongsTo(models.ModelName, { foreignKey: 'your_key', as:'your_identifier' } )
然后,当您对方法执行include时,您也会调用标识符:
await db.services_user_prices.findOne({
where: { is_active: 1, user_id: 123 },
include:[{
model: db.services_prices
as: 'your_identifier'
}]
});
如果未定义foreignKey
字段,则as
字段将设置列名称。
好吧,如果你使用sequelize,那么你需要更新你的模型,因为
默认情况下,sequelize将寻找带有模型名称的外键启动
你已经将bundle_price_id
定义为services_prices
的外键。
您需要将列名更改为services_price_id
然后它将得到修复。
或者如果你想使用bundle_price_id
,你需要在你的模型关系中定义它。
Model.belongsTo(models.ModelName, { foreignKey: 'your_key'} )
如果您需要提出任何其他要求,请随意。