node.js - Sequelize.js:一对多关系与自定义字段的热切加载

标签 node.js express sequelize.js

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

所以我可以在 View 中访问它(现在我得到一个空字符串):

#{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'});

谢谢大家

最佳答案

可能是这样:

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

关于node.js - Sequelize.js:一对多关系与自定义字段的热切加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594151/

相关文章:

javascript - 从 Express 路由器中排除公用文件夹

node.js - express / Jade /哈巴狗 : Calling a javascript object's functions

javascript - TypeError : window. scroll is not a function 类型错误: window. scroll is not a function in server side rendering

node.js - 为 sequelize findAll 添加限制会破坏查询吗?

node.js - 运行 Mocha 测试时更改默认的 TypeScript 配置文件

node.js - npm 全局安装链接到错误的目录

javascript - 从 Mongoose 查询创建对象

sql-server - 如何将对象数组插入映射表 - Sequelize

javascript - Sequelize.js 创建太多回调

javascript - DynamoDB DeleteItem 显然不起作用 - 没有给出错误