【问题标题】:Sequelize - Counting associations and fetching data from association with querySequelize - 计算关联并从与查询的关联中获取数据
【发布时间】:2021-06-05 11:27:43
【问题描述】:

我正在使用 sequelize(Postgres 作为数据库)创建一个类似 Twitter 的应用程序。有 3 个表 - 用户、帖子和帖子喜欢。现在,在列出帖子时,我想获取喜欢的总数,并且当前用户是否喜欢该帖子。那么如何通过 sequelize 实现呢?

我创建了一个简单的查询,但不知道下一步该做什么。 postlikes 表有 postId 和 userId。我将用户包含在以下查询中以获取帖子作者的数据。

let allPosts = await db.Post.findAndCountAll({
      order: [['createdAt', 'DESC']],
      offset: offset * limit,
      limit: limit,
      include: [
        {
          model: db.User,
          as: 'user',
          attributes: ['id', 'firstName', 'lastName', 'username', 'profilePic'],
          raw: true,
        },
        {
          model: db.PostLike,
          as: 'postlikes',
          raw: true,
        },
      ],
    });

我在stackoverflow上找到了以下代码并尝试了但没有得到任何结果:

attributes: [
        [
          db.Sequelize.fn('COUNT', db.Sequelize.col('postlikes.id')),
          'likeCount',
        ],
      ],

得到这个错误-原始:错误:缺少表“postlikes”的 FROM 子句条目

所以请帮助我。提前致谢。

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    型号:Post.js

    "use strict";
    const { Model } = require("sequelize");
    module.exports = (sequelize, DataTypes) => {
        class Post extends Model {
            static associate(models) {
                this.hasMany(models.PostLike, {
                    foreignKey: "postId",
                    as: "postlikes",
                });
            }
        }
        Post.init({
            type: { type: DataTypes.STRING },
        }, {
            sequelize,
            modelName: "Post",
        });
        return Post;
    };
    

    型号:PostLike.js

    "use strict";
    const { Model } = require("sequelize");
    module.exports = (sequelize, DataTypes) => {
        class PostLike extends Model {
            static associate(models) {
                this.belongsTo(models.Post, {
                    foreignKey: "postId",
                    as: "post",
                });
            }
        }
    
        PostLike.init({
            postId: { type: DataTypes.INTEGER },
        }, {
            sequelize,
            modelName: "PostLike",
        });
        return PostLike;
    };
    

    控制器

    var post = await db.Post.findAll({
        attributes: [
            'id',
            [db.Sequelize.fn('COUNT', db.Sequelize.col('postlikes.id')), 'likeCount',],
        ],
        include: ['postlikes']
    })
    console.log(JSON.parse(JSON.stringify(post)))
    process.exit()
    

    输出:

    [ { id: 1, likeCount: 56, postlikes: [ [Object] ] } ]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    相关资源
    最近更新 更多