我正在使用node,express,sequelize编写应用程序,我有一点问题。我试图在关系的“一部分”上加载模型。
我得到这个SQL:
Executing: SELECT `albaran`.*, `cliente`.`ClienteID` AS `cliente.ClienteID`,
`cliente`.`NombreES` AS `cliente.NombreES` FROM `albaran` LEFT OUTER JOIN `cliente` AS
`cliente` ON `albaran`.`AlbaranNo` = `cliente`.`ClienteID` WHERE
`albaran`.`AlbaranNo`='2013100001';
我需要它:
Executing: SELECT `albaran`.*, `cliente`.`ClienteID` AS `cliente.ClienteID`,
`cliente`.`NombreES` AS `cliente.NombreES` FROM `albaran` LEFT OUTER JOIN `cliente` AS
`cliente` ON `albaran`.`ClienteID` = `cliente`.`ClienteID` WHERE
`albaran`.`AlbaranNo`='2013100001';
所以我可以在视图中访问它(现在我得到一个空字符串):
#{albaran.cliente.NombreES}
这是代码:
albaran.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Albaran", {
AlbaranNo: { type: DataTypes.BIGINT, primaryKey: true},
ClienteID: {
type: DataTypes.STRING, //this must be string, I am not who defined the db
references: "Cliente",
referencesKey: "ClienteID"
}},{
timestamps: false,
freezeTableName: true,
tableName: 'albaran'
})
}
cliente.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Cliente", {
ClienteID: {
type: DataTypes.STRING, primaryKey: true
},
NombreES: DataTypes.STRING
},{
timestamps: false,
freezeTableName: true,
tableName: 'cliente'
})
}
协会
db.Albaran.hasOne(db.Cliente, {as: "cliente", foreignKey: 'ClienteID'});
路由器
exports.albaran = function(req, res) {
db.Albaran.findAll({ include: [{ model: db.Cliente, as: "cliente" }]})
.success(function (albaranes){
res.render("albaranes", {albaranes: albaranes});
});
};
非常感谢你。我希望我能清楚地解释自己。
版:
我找到了修改关联的解决方案:
db.Albaran.belongsTo(db.Cliente, {as: "cliente", foreignKey: 'ClienteID', primaryKey: 'ClienteID'});
db.Cliente.hasMany(db.Albaran, {as: "albaranes", foreignKey: 'ClienteID'});
谢谢大家
答案 0 :(得分:2)
可能是这样:
db.Cliente.hasMany(db.Albaran, {as: "albaran", foreignKey: 'ClienteID'});
此处有更多信息:http://sequelizejs.com/documentation#associations-one-to-many
另一方是:
db.Albaran.hasOne(db.Cliente,{as:“cliente”,foreignKey:'AlbaranNo“});