簡體   English   中英

選擇節點q的當前值后如何增加postgres表列?

[英]How to increment postgres table column after selecting the current value qith Node pg?

我正在創建一個具有用戶,問題,答案,評論和投票表的應用程序。 不知道這是否是一個好決定,但是我決定將投票表變成一個包含所有其他表的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列的最初想法?

您已將questionVoteCount聲明為SERIAL類型,這意味着自動遞增。 看起來您想要做的就是將其定義為INTEGER

表格更新-感謝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”語句不同,對我來說,使用'INSERT'-將“ voteCount”帶有1代表upvote和-1代表downvote。

現在,我可以運行“ SELECT SUM(“ voteCount”)”以獲取問題,答案,評論,用戶以及其他所有問題的所有票。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM