我需要从现有数据库中检索两个关联模型的值。
模特大师
"use strict";
module.exports = (sequelize, DataTypes) => {
var MasterPurchaseOrder = sequelize.define('master_purchase_order' , {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
requestedById: {
type: DataTypes.INTEGER(11),
allowNull: true,
field: 'requested_by_id'
},
status: {
type: DataTypes.STRING,
allowNull: true,
field: 'status'
}
},{
classMethods:{
associate: (models) =>{
MasterPurchaseOrder.hasMany(models.purchase_order,{
as: 'purchase_order',
foreignkey: 'master_purchase_order_id'
});
},
},
}, {
timestamps: true,
paranoid: false,
underscored: true,
freezeTableName: true,
tableName: 'master_purchase_orders'
});
return MasterPurchaseOrder;
}
采购订单模型
"use strict";
module.exports = (sequelize, DataTypes) => {
var PurchaseOrder = sequelize.define('purchase_order' , {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
purchaseDate: {
type: DataTypes.DATE,
allowNull: true,
field: 'purchase_date'
},
requestedById: {
type: DataTypes.INTEGER(11),
allowNull: true,
field: 'requested_by_id'
},
masterPurchaseOrderId: {
type: DataTypes.INTEGER(11),
allowNull: true,
field: 'master_purchase_order_id'
}
},{
classMethods:{
associate: (models) => {
PurchaseOrder.belongsTo(models.master_purchase_order,{
as: 'master_purchase_order',
foreignkey: 'master_purchase_order_id'
});
},
},
}, {
timestamps: true,
paranoid: false,
underscored: true,
freezeTableName: true,
tableName: 'purchase_orders'
});
return PurchaseOrder;
}
这是我的采购订单控制器:
"using strict";
const purchaseOrder = require('../models/').purchase_order;
const MasterPurchaseOrder = require('../models/').master_purchase_order;
module.exports= {
index(req, res) {
purchaseOrder
.findAll({
include:[
{model: MasterPurchaseOrder, as: 'master_purchase_order'}
]
})
.then((masters) => {
res.status(200).json(masters);
});
// .catch((error) => {
// res.status(500).json(error);
// });
},
};
我收到错误:
未处理拒绝错误:master_purchase_order (master_purchase_order)与purchase_order没有关联!
任何建议
答案 0 :(得分:0)
我在我的子模型中覆盖了classMethods定义。
{
classMethods:{
associate: (models) => {
PurchaseOrder.belongsTo(models.master_purchase_order,{
as: 'master_purchase_order',
foreignkey: 'master_purchase_order_id'
});
associate: (models) => {
PurchaseOrder.belongsTo(models.suuplier,{
as: 'supplier',
foreignkey: 'supplier_id'
});
},
},
}
正确的方法是:
{
classMethods:{
associate: (models) => {
PurchaseOrder.belongsTo(models.master_purchase_order,{
as: 'master_purchase_order',
foreignkey: 'master_purchase_order_id'
});
PurchaseOrder.belongsTo(models.suuplier,{
as: 'supplier',
foreignkey: 'supplier_id'
});
},
}