gpt4 book ai didi

node.js - Sequelize findAndCountAll 并计算包含的模型

转载 作者:行者123 更新时间:2023-12-05 07:16:52 27 4
gpt4 key购买 nike

我使用 postgresql/sequelize 和 findAndCountAll 函数。

   Entry.findAndCountAll({
where: {TitleId: title.id},
include: [
{model: User, as: 'users', attributes: ['username']},
{model: EntryHasLike} // I need to count this. model.
],
offset: 15 * (req.body.page - 1),
limit: 15
}).then(entries => {
res.json({
title: title,
count: entries.count,
entries: entries.rows // [I want to count of likes inside this table]
})
}).catch(err => {}

我正在使用 findAndCountAll 对条目进行计数,但我还想对与 Entries.Id 相同的 EntryHasLikes 模型进行计数。

EntryHasLike 模型:

'use strict';
module.exports = (sequelize, DataTypes) => {
const EntryHasLike = sequelize.define('EntryHasLike', {
EntryId: {
type:DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
UserId: {
type:DataTypes.INTEGER,
allowNull: false
},
likeDate: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
},{
timestamps: false
});
EntryHasLike.associate = function(models) {
EntryHasLike.belongsTo(models.User)
EntryHasLike.belongsTo(models.Entry)
};
return EntryHasLike;
};

入门模型:

'use strict';
module.exports = (sequelize, DataTypes) => {
const Entry = sequelize.define('Entry', {
UserId: {
type: DataTypes.INTEGER,
allowNull: false
},
entry: {
type: DataTypes.TEXT,
allowNull: false
},
entryRev: {
type: DataTypes.STRING,
defaultValue: 1
},
entryRefId: {
type: DataTypes.INTEGER,
defaultValue: null
},
entryCondition: {
type: DataTypes.INTEGER,
defaultValue: 1
},
activity: {
type: DataTypes.INTEGER,
defaultValue: 1
},
TitleId: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {});
Entry.associate = function(models) {
Entry.belongsTo(models.Title, {foreignKey: 'TitleId', as: 'titles'})
Entry.belongsTo(models.User, {foreignKey: 'UserId', as: 'users'})
Entry.belongsToMany(models.EntryCat, {through: 'EntryHasCats', as: 'entrycats'})
Entry.belongsToMany(models.EntryTag, {through: 'EntryHasTags', as: 'entrytags'})
Entry.hasMany(models.EntryHasLike)
};
return Entry;
};

我尝试了很多解决方案,但我无法得到结果。正如您在下面看到的相关问题,但都是关于 findAll 函数的。我的函数是 findAndCountAll

Counting associated entries with Sequelize

Sequelize 'hasMany' associated(model) count in attributes in query execution

最佳答案

也许在客户端你可以获取 Entry.EntryHasLike

的长度
setEntry(data) {
this._entry = {
...data,
count: data.EntryHasLike.length
}
}

关于node.js - Sequelize findAndCountAll 并计算包含的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004694/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com