Sequelize查询两张表
Sequelize query two tables
我有两个表的关联。一个是帐户,另一个是订单。 Orders.belongsTo(帐户)和 Account.hasMany(订单)。两个表共享一个外键 'order_user_id'。我能够像这样在 class 方法中附加外键:
classMethods: {
associate: function(models) {
// associations can be defined here
Orders.belongsTo(models.Accounts, {foreignKey: 'order_user_id'});
}
}
我目前正在传递这个查询,
models.Orders.findAll({
where: {'orderStatus' : req.query.orderStatus},
limit: req.query.limitTo,
include: [models.Accounts],
order: 'orderDateAdded DESC'
}).then( function (orders, error) {
if(error) {
return res.send(error);
}
console.log(orders);
});
这仅 returns json 包含订单详细信息以及 'order_user_id',但希望访问帐户的更多属性。我该如何实现?
我解决了我的问题。我在包含中缺少必需的属性,如下所示:
include: [ {model: models.Accounts, required: true} ]
填充的帐户对象。 :)
我有两个表的关联。一个是帐户,另一个是订单。 Orders.belongsTo(帐户)和 Account.hasMany(订单)。两个表共享一个外键 'order_user_id'。我能够像这样在 class 方法中附加外键:
classMethods: {
associate: function(models) {
// associations can be defined here
Orders.belongsTo(models.Accounts, {foreignKey: 'order_user_id'});
}
}
我目前正在传递这个查询,
models.Orders.findAll({
where: {'orderStatus' : req.query.orderStatus},
limit: req.query.limitTo,
include: [models.Accounts],
order: 'orderDateAdded DESC'
}).then( function (orders, error) {
if(error) {
return res.send(error);
}
console.log(orders);
});
这仅 returns json 包含订单详细信息以及 'order_user_id',但希望访问帐户的更多属性。我该如何实现?
我解决了我的问题。我在包含中缺少必需的属性,如下所示:
include: [ {model: models.Accounts, required: true} ]
填充的帐户对象。 :)