我有两个模型,policyTable
和policy_rule
定义如下。 policy_id
中有一个名为policy_rule
的列,它是外键并引用id
中的policyTable
列。 policy_rule
可以有多个policyTable
,即存在1:N的关系。
var policyTable = dbController.db.define('policyTable', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
't': {
type: Sequelize.BIGINT,
unique: true
},
'name': {
type: Sequelize.STRING,
},
src: {
type: Sequelize.STRING
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'zo_policy',
});
var policy_rule = dbController.db.define('policy_rule', {
policy_id: {
type: Sequelize.BIGINT,
references: {
model: policyTable,
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
agent_id: {
type: Sequelize.BIGINT,
},
enabled: {
type: Sequelize.BOOLEAN,
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'zo_policy_rule',
});
现在我想加入这两个模型并获取它们的所有列。我怎样才能做到这一点?我尝试了以下代码,但它说
错误:policy_rule与policyTable没有关联!
function getAllPolicies() {
return policyTable.findAndCountAll({
include: [{
model: policy_rule
}]
}).then(function (users) {
console.log(users);
data.count = users.count;
data.users = users.rows;
console.log(data);
return data;
});
};
答案 0 :(得分:1)
即使您的关联是在数据库级别定义的,并且您在列定义中指明了这一点,但要使用sequelize的include
功能,您仍需要明确定义模型之间的关联。
这里是doco中的相关部分:http://docs.sequelizejs.com/en/latest/docs/associations/#belongsto 和 http://docs.sequelizejs.com/en/latest/docs/associations/#1m
在您的情况下,它意味着将代码调整为下面的内容 - 请注意每个模型定义中的新classMethods
部分:
var policyTable = dbController.db.define('policyTable', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
't': {
type: Sequelize.BIGINT,
unique: true
},
'name': {
type: Sequelize.STRING,
},
src: {
type: Sequelize.STRING
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'zo_policy',
classMethods: {
associate(models) {
this.hasMany(models.policy_rule, {foreignKey: 'policy_id'})
}
}
});
var policy_rule = dbController.db.define('policy_rule', {
policy_id: {
type: Sequelize.BIGINT,
references: {
model: policyTable,
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
agent_id: {
type: Sequelize.BIGINT,
},
enabled: {
type: Sequelize.BOOLEAN,
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'zo_policy_rule',
classMethods: {
associate(models) {
this.belongsTo(models.policyTable, {foreignKey: 'policy_id'})
}
}
});