我在使用.findOne方法中的include获取用户订单时遇到问题。 SQL查询是正确的,它返回50行,但是sequelize给了我一个带有空值对象的数组:
orders:
[ Order {
dataValues: {},
_previousDataValues: {},
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
有我的模特:
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
steamid: DataTypes.STRING,
name: DataTypes.STRING,
img: DataTypes.STRING,
tradelink: DataTypes.STRING,
ban_chat: DataTypes.INTEGER,
block_sms: DataTypes.INTEGER,
balance: DataTypes.INTEGER,
ref: DataTypes.STRING,
refcode: DataTypes.STRING,
ip_address: DataTypes.STRING
}, {
timestamps: false
});
User.associate = function(models) {
// associations can be defined here
User.hasMany(models.Order,{
foreignKey: 'steamid',
sourceKey: 'steamid',
as: 'orders'
});
};
return User;
};
const customDataTypes = require('../../core').SequelizeTimestamp;
module.exports = (sequelize, DataTypes) => {
var Order = sequelize.define('Order', {
steamid: DataTypes.STRING,
item_name: DataTypes.STRING,
price: DataTypes.FLOAT,
type: DataTypes.STRING,
website: DataTypes.STRING,
amount: DataTypes.INTEGER,
status: DataTypes.INTEGER,
img: DataTypes.STRING,
send_attempts: DataTypes.INTEGER,
message: DataTypes.STRING,
date: customDataTypes.TIMESTAMP,
}, {
timestamps: false
});
Order.associate = function(models) {
// associations can be defined here
Order.belongsTo(models.User, {
foreignKey: 'steamid',
targetKey: 'steamid',
as: 'user'
})
};
return Order;
};
在我的API中,我想获取用户及其订单。 因此,在控制器中,我正在这样做:
user.findOne({
where: { steamid: req.params.steamId },
include: [{
model: order,
as: 'orders',
limit: 50
}],
})
对于include sequelize,执行以下查询:
SELECT `id`, ... FROM `Orders` AS `Order` WHERE `Order`.`steamid` IN ('123456') LIMIT 50;
当我执行它时,我成功获得了50行,但是当我在控制台日志user.dataValues
中得到:
{ id: 1,
steamid: '123456',
name: 'TEST',
img: null,
balance: 40575,
orders:
[ Order {
dataValues: {},
_previousDataValues: {},
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false } ] }
当我执行user.getOrders()
时,它已经成功向我发出了用户订单,但查询与包含查询有些不同:
SELECT `id`, ... FROM `Orders` AS `Order` WHERE `Order`.`steamid` = '123456';
所以我也不明白为什么这个查询使用“ =”,但是来自include的查询使用“ IN()”
答案 0 :(得分:0)
//this will get json result from your already executed sequlize query, as you can see in your output
user.dataValues;
//this will run the query to get al the order of user you found from the query output
user.getOrders();
我认为您对SequlizeJson对象感到困惑,因为您正在订单数组中,您可以使用raw :true
和nest : true
:
尝试在查询下面运行
user.findOne({
where: { steamid: req.params.steamId },
include: [{
model: order,
as: 'orders',
limit: 50
}],
raw:true, // <----- HERE
nest:true // <----- HERE
})