gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:55:12 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com