我正在创建一个具有用户、问题、答案、评论和投票表的应用程序。不确定这是否是一个好的决定,但我决定将投票表变成一个包含所有其他表的 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 列?