从sequelize关联中计数父行和子行

时间:2019-07-04 14:14:56

标签: javascript node.js sequelize.js associations

我是新手,我试图获取hasMany关联的评论和对这些评论的回复,并且必须计算父评论和对我收到的每个评论的回复

我正在使用sequelize findAndCountAll来计数父注释行,现在计算出我正在使用的每个注释的回复都可以正常工作

attributes:{include: [[mysql.sequelize.fn("COUNT", mysql.sequelize.col("comment.comment_id")), "Count"]]}

计算第一条评论的回复次数,但得到的却给出了其余的父评论

model
    const comment = model.comment;

    comment.hasMany(comment,
        {
            foreignKey: 'parentCommentId',
            as: "replies"
        });

query
function findWhere(where, pagination){

    return mysql.comment.findAndCountAll({
        where,
        offset: pagination.offset,
        limit: pagination.count,

        // attributes:{include: [[mysql.sequelize.fn("COUNT", mysql.sequelize.col("comment.comment_id")), "Count"]]},

        include: [{
            model: mysql.comment,
            as: "replies",
            offset: 0,
            limit: 1
        }]

    });
}

这是它给出的答复

{
    "count": 10,
    "rows": [
        {
            "commentId": 2,
            "userId": 7,
            "postId": 1,
            "mediaId": null,
            "commentText": "2 Updated Wao amazing post 13",
            "parentCommentId": null,
            "createdAt": "2019-07-01T05:20:00.000Z",
            "updatedAt": "2019-07-04T02:35:49.000Z",
            "Count": 10,
            "replies": [
                {
                    "commentId": 4,
                    "userId": 7,
                    "postId": null,
                    "mediaId": null,
                    "commentText": "Wao amazing post",
                    "parentCommentId": 2,
                    "createdAt": "2019-07-02T04:08:29.000Z",
                    "updatedAt": "2019-07-02T04:08:29.000Z"
                }
            ]
        }
    ]
}

这是错误的,因为它没有显示其余的父注释

问题出在此

attributes:{include: [[mysql.sequelize.fn("COUNT", mysql.sequelize.col("comment.comment_id")), "Count"]]}

0 个答案:

没有答案