我正在尝试按关联模型的计数进行排序,但从 Sequelize 收到以下错误
Cannot read property '_modelAttribute' of undefined
我有以下代码:
db.user.belongsToMany(db.user, {
as: "User",
through: "UserFollowers",
foreignKey: "user_id"
});
db.user.belongsToMany(db.user, {
as: "Follower",
through: "UserFollowers",
foreignKey: "follower_id"
});
和
User.findAll({
attributes:["username",db.sequelize.literal('(SELECT COUNT(*) FROM "public"."Users","public"."UserFollowers" WHERE "Users".user_id = "UserFollowers".user_id GROUP BY "Users".user_id)'),'followercount'],
include:[{model:User,as:'Follower'}],
order:[{ model: User, as: 'Follower' }[db.sequelize.literal('followercount')],'DESC']
}).then(users => {
res.json(users)
})
感谢您的帮助!
最佳答案
从代码上看,问题似乎出在排序子句上。 将其更改为:
order: [[{ model: User, as: 'Follower' }, 'followercount', 'DESC']]
如果这不能解决问题,请尝试通过添加 logging: console.log
来记录查询结果。这应该可以帮助您通过分析 sql 查询来确定失败的部分。
关于javascript - Sequelize : TypeError: Cannot read property '_modelAttribute' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476696/