我正在尝试按关联模型的数量进行排序,并且一直从Sequelize获得以下错误
无法读取未定义的属性'_modelAttribute'
我有以下代码:
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)
})
感谢您的帮助!
答案 0 :(得分:0)
通过浏览代码,问题似乎出在ordering子句上。 更改为:
order: [[{ model: User, as: 'Follower' }, 'followercount', 'DESC']]
如果这样不能解决问题,请尝试通过添加logging: console.log
记录查询结果。这应该可以帮助您通过分析sql查询来确定哪些部分失败了。