如何在seqeulize中使用包含关联的组?
型号:
消息模型:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Messages = sequelize.define('Messages', {
roomId: DataTypes.INTEGER,
senderId: DataTypes.INTEGER,
message: DataTypes.STRING
}, {});
Messages.associate = function (models) {
Messages.belongsTo(models.Users, {
foreignKey: 'senderId'
});
};
return Messages;
};
用户模型:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
phone: {
type: DataTypes.STRING(15),
unique: true
},
token: DataTypes.STRING,
}, {});
Users.associate = function (models) {};
return Users;
};
首先,我使用这样的方式对一些列进行分组
function getMessagesByUser(req, res) {
Messages.findAll({
attributes: ['id', 'senderId', 'roomId', [sequelize.fn('MAX', sequelize.col('createdAt')), 'createdAt']],
group: ['roomId'],
order: [
[sequelize.fn('max', sequelize.col('createdAt')), 'ASC'],
]
}).then(messages => {
res.status(200).json({
success: true,
result: messages
});
});
}
上面的代码有效,但是我想包含一个用户模型
include: [{ model: Users,
attributes: []
}],
但是它不起作用...我想按日期将聊天室排序,将其分组并添加用户。