【发布时间】:2017-09-04 01:08:18
【问题描述】:
说明
我有一个由客户、地址和订单组成的简单数据库。我正在尝试查找地址为某个字符串的所有订单。例如,我可以提供城市或州,并且我想以此为基础进行查找。
订单模型:
module.exports = db.define('orders', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
repId: { type: Sequelize.INTEGER },
totalItemCost: { type: Sequelize.DECIMAL(10,2), allowNull: false},
shippingCost: { type: Sequelize.DECIMAL(10,2), allowNull: false},
orderDate: { type: Sequelize.DATE, allowNull: false},
isPaid: { type: Sequelize.BOOLEAN, allowNull: false},
taxPercentage: { type: Sequelize.DECIMAL(10,4), allowNull: false},
}, {timestamps: false, freezeTableName: true, tableName: 'Orders'});
地址模型:
module.exports = db.define('address', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
firstName: { type: Sequelize.STRING, allowNull: false},
lastName: { type: Sequelize.STRING, allowNull: false},
city: { type: Sequelize.STRING, allowNull: false},
address: { type: Sequelize.STRING(256), allowNull: false},
zip: { type: Sequelize.STRING(10), allowNull: false},
}, {timestamps: false, freezeTableName: true, tableName: 'Address'});
关系:
var models = {};
models.Address = require("./models/address.js");
models.Customer = require("./models/customer.js");
models.Orders = require("./models/orders.js");
// Orders Relations
models.Orders.belongsTo(models.Customer, { foreignKey: { name: 'customerId', allowNull: false }});
models.Orders.belongsTo(models.Address, { foreignKey: { name: 'shippingAddressId', allowNull: false }});
问题
例如,我想查找城市为 Birchwood 的所有订单。我在我的 findAll 命令中使用 include 并将模型设置为我的地址,并且因为我专门命名了我的送货地址,所以设置了“as”语句。这导致页面永远不会加载,我不确定我做错了什么。如果我删除包含命令,我的所有订单都可以正常加载。当使用“belongsTo”时,我没有看到任何包含的示例。当使用“hasMany”时,看起来像使用“association”而不是“foreign_key”。这就是为什么“as”不起作用的问题吗?
models.Orders.findAll({
where: where,
include: [{
model: models.Address,
as: 'shippingAddressId',
}]
}).then(function(orders) {
res.json(orders);
}).catch(function(err) {
res.status(500).json({"error": err});
});
编辑 1
我为查询语句添加了错误处理,但现在只输出 {"error":{}}。错误是空白的,所以这不是很有帮助。如果我删除“as:'shippingAddressId'”行,则模型会加载,并将地址放在不需要的 json 结构中的“地址”字段下。添加 where 子句会导致它返回一个空对象 {}。我基本上想要包括:[{ all: true, nested: true }] 但也过滤了关系地址。
【问题讨论】:
-
json({"error": err});有问题。err必须包含堆栈跟踪和错误消息。即使解决了这个特定问题,我仍然建议您在调试器中调试代码。看看那里显示什么错误。并且至少找到打印错误到控制台的方法。喜欢console.dir(err)
标签: javascript node.js sequelize.js