[英]Sequelize n:m association - Voting system - cannot set attribute of join table
I'm trying to implement a voting system so users of my app can vote on other users responses to a question. 我正在尝试实施投票系统,以便我的应用程序的用户可以对其他用户对问题的回答进行投票。
It is a Node app using Express and Sequelize on the back-end, for the moment I'm using a SQLite database for ease of testing. 这是一个在后端使用Express和Sequelize的Node应用程序,目前我正在使用SQLite数据库来简化测试。
Here's the relevant parts of my models: 这是我模型的相关部分:
// in user.js
User.associate = function (models) {
// ...
models.User.belongsToMany(models.Response, {
through: models.Vote,
as: 'Votes'
})
}
// in response.js
Response.associate = function (models) {
// ...
models.Response.belongsToMany(models.User, {
through: models.Vote,
as: 'Votes'
})
}
// in vote.js
module.exports = (sequelize, DataTypes) => {
return sequelize.define('Vote', {
upVote: {
type: DataTypes.BOOLEAN,
allowNull: false
}
})
}
So now in my votes.js
controller file I may try and create a new vote, given a UserId
and a ResponseId
as so: 所以现在在我的votes.js
控制器文件中,我可以尝试创建一个新的投票,给定一个UserId
和一个ResponseId
:
const user = await User.findById(req.user.id)
const response = await Response.findById(req.params.responseId)
await response.addVote(user, {
upVote: true
})
res.send(await response.getVotes())
The problem is, although the Votes
join table is created correctly, and although I am passing the addVote
function a boolean directly indicating what value the upVote
attribute should store, I just get an error stating that notNull Violation: Vote.upVote cannot be null
. 问题是,尽管Votes
addVote
表已正确创建,并且尽管我向addVote
函数传递了一个布尔值,该布尔值直接指示upVote
属性应存储的值,但我只是收到一条错误消息,指出notNull Violation: Vote.upVote cannot be null
。
The only reason I added the not null constraint to begin with was because without it, I just received a vote with a null value for upVote
. 我之所以添加not null约束的唯一原因是因为没有它,我刚刚收到了对upVote
具有空值的upVote
。
Does anyone have any idea why this might be happening? 有谁知道为什么会这样?
I don't know exactly why, but replacing the response.addVote
with this: 我不知道为什么,但是用这个替换了response.addVote
:
const vote = await Vote.create({
upVote: req.body.upVote,
UserId: req.user.id,
ResponseId: req.params.responseId
})
res.send(vote)
Works fine. 工作正常。 Odd. 奇。 I keep running into issues where the so-called 'magic' auto-generated functions that Sequelize is supposed to provide for relations either aren't available or don't work. 我一直遇到一些问题,Sequelize应该提供所谓的“魔术”自动生成的函数来提供关系,这些函数要么不可用,要么不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.