3

我正在用 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'
        })
     } 

客户端.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'});

谢谢大家

4

1 回答 1

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"});

于 2013-10-26T10:24:45.860 回答