postgresql 对findAndCountAll进行序列化并计算包含的模型

tkclm6bt  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(142)

我使用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对条目进行计数,但我还想对EntryHasLikes模型进行计数,这与Entrys. Id相同。

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

ru9i0ody

ru9i0ody1#

也许在客户端上,您可以取Entry.EntryHasLike的长度

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

相关问题