我有两个表,类别和UserMedia,我正在尝试编写一个sequelize查询,返回类别和唯一userMedia.userId的计数,其中category.id == userMedia.categoryId
const { language } = request.query;
let options = {
limit: 30,
where: { language },
order: [['official', 'DESC']],
attributes: [
'id',
'official',
'name',
[database.fn('count', database.col('userMedia.userId')), 'count'],
],
include: [{
model: UserMediaModel,
as: 'userMedia',
attributes: [
'userId',
],
}],
group: ['id'],
};
CategoryModel.findAll(options).then(categories => {
response.success(categories);
}).catch(next);
});
但是当我添加该行时,我不断收到“字段列表'中的错误列”userMedia.userId“:
[database.fn('count', database.col('userMedia.userId')), 'count'],
当我将它添加到include字段时,我得到“在没有GROUP BY的聚合查询中,SELECT列表的表达式#1包含非聚合列'category.id';这与sql_mode = only_full_group_by不兼容”
只是使用count函数执行include工作正常,因为我看到另一个表与查询一起返回,但我可以弄清楚如何只返回该表而不是整个表的计数 .
这是我的两个模型:
const CategoryModel = database.define('category', {
id: {
type: Sequelize.INTEGER(10).UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: 'compositeNameLanguageIndex',
},
language: {
type: Sequelize.STRING(3), // ISO-639
allowNull: false,
unique: 'compositeNameLanguageIndex',
},
official: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false,
},
});
const UserMedia = database.define('userMedia', {
id: {
type: Sequelize.INTEGER(10).UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
userId: {
type: Sequelize.INTEGER(10).UNSIGNED,
allowNull: false,
},
categoryId: {
type: Sequelize.INTEGER(10).UNSIGNED,
allowNull: false,
},
type: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isIn: {
args: [ types ],
msg: 'The type provided is invalid',
},
},
},
crop: {
type: Sequelize.JSON,
allowNull: false,
validate: {
isValidSchema(value) {
Joi.assert(value, Joi.object({
top: Joi.number().required(),
left: Joi.number().required(),
width: Joi.number().required(),
height: Joi.number().required(),
}));
},
},
},
urls: {
type: Sequelize.JSON,
allowNull: false,
validate: {
isValidSchema(value) {
Joi.assert(value, Joi.object({
original: Joi.string().required(),
transformed: Joi.object().required(),
}));
},
},
},
});
我在其他地方创建了员工:
CategoryModel.hasMany(UserMediaModel, { foreignKey: 'categoryId' });
一直苦苦挣扎,所以任何帮助都会受到赞赏