0

我正在创建一个具有用户、问题、答案、评论和投票表的应用程序。不确定这是否是一个好的决定,但我决定将投票表变成一个包含所有其他表的 ID 的连接表,而不是让每个其他表都有一个 vote_count 列,因为投票将属于所有其他表。

投票表是这样的——

    CREATE TABLE vote (
     "questionVoteCount"       SERIAL,
     "answerVoteCount"         SERIAL,
     "commentVoteCount"        SERIAL,
     "accountId"               INTEGER REFERENCES account(id),
     "questionId"              INTEGER REFERENCES question(id),
     "answerId"                INTEGER REFERENCES answer(id),
     "commentId"               INTEGER REFERENCES comment(id),
     PRIMARY KEY ("questionVoteCount", "answerVoteCount", 
     "commentVoteCount")
     );

我的模型看起来像这样-

    class Vote {
constructor({
    questionVoteCount,
    answerVoteCount,
    commentVoteCount,
    accountId,
    questionId,
    answerId,
    commentId
} = {}) {
    this.questionVoteCount =
        this.questionVoteCount || VOTE_DEFAULTS.questionVoteCount
    this.answerVoteCount = this.answerVoteCount || VOTE_DEFAULTS.answerVoteCount
    this.commentVoteCount =
        this.commentVoteCount || VOTE_DEFAULTS.commentVoteCount
    this.accountId = accountId || VOTE_DEFAULTS.accountId
    this.questionId = questionId || VOTE_DEFAULTS.questionId
    this.answerId = answerId || VOTE_DEFAULTS.answerId
    this.commentId = commentId || VOTE_DEFAULTS.commentId
}

static upVoteQuestion({ accountId, questionId }) {
    return new Promise((resolve, reject) => {
        pool.query(
            `UPDATE vote SET "questionVoteCount" = 
                               "questionVoteCount" + 1 WHERE 
                               "questionId" = $1 AND "accountId" = 
                               $2`,
            [questionId, accountId],
            (err, res) => {
                if (err) return reject(err)
                resolve()
            }
        )
    })
}

我希望每个问题/答案/评论都有一个投票计数,并且在投票路线上发布的用户会增加或减少上述任何一项的投票。我该怎么做呢?我有一种感觉,我对投票表本身犯了一些错误。我是否应该坚持我最初的想法,即在每个表中都有一个 vote_count 列?

4

2 回答 2

1

您声明questionVoteCount为类型SERIAL,这意味着自动增量。看起来您想要做的是将其定义为INTEGER.

于 2019-04-17T03:29:00.717 回答
0

更新表-感谢 alfasin

CREATE TABLE vote (
 "questionVoteCount"       INTEGER DEFAULT 0 NOT NULL,
 "answerVoteCount"         INTEGER DEFAULT 0 NOT NULL,
 "commentVoteCount"        INTEGER DEFAULT 0 NOT NULL,
 "accountId"               INTEGER REFERENCES account(id),
 "questionId"              INTEGER REFERENCES question(id),
 "answerId"                INTEGER REFERENCES answer(id),
 "commentId"               INTEGER REFERENCES comment(id),

);

而不是运行''UPDATE'语句,'I​​NSERT'-ing'voteCount' 1 表示赞成,-1 表示反对对我有用。

现在我可以运行'SELECT SUM("voteCount")' 来获得问题、答案、评论、用户等的所有选票。

于 2019-04-20T02:24:30.140 回答