如何确保用户每个帖子只能投票一次
我正在建立一个网站,其功能类似于 SE 的投票系统。我试图限制用户在每个帖子上投票多次。
目前,我正在考虑在我的 user
mysql 数据库中添加一个字段,用于保存用户已投票的 id
列表(对应于帖子)。每次用户投票时,都会根据当前帖子的 id
检查该数组。如果找到,则会显示一条错误消息,如果没有,则投票通过,并且 id
现在是用户“已投票”列表的一部分。
这似乎是一种奇怪的做法。这是一种有效的方法吗?什么方法会更好/最好?
I'm building a website which has a feature which ressembles SE's voting system. I'm trying to restrict users from voting more than once per post.
Currently, I was thinking of having a field in my user
mysql database that would keep a list of id
s (corresponding to posts) that the user has already voted on. Each time the user casts a vote, the array is checked against the current post's id
. If it is found an error message is displayed, if not the vote goes through and the id
is now part of the user's "already voted on" list.
This seems like an odd way of doing this. Is it an efficient method? What method would be better/best?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将创建一个名为 user_post 的单独表,其中包含 user_id 和 post_id - 事实上,您可以将这些列设为多列主键。
当用户对帖子投票时,您可以使用以下查询:
Replace 本质上是说“插入,除非存在唯一键冲突,如果有,则更新行”。或者,您可以使用:
本质上是“插入,除非存在唯一的键冲突,如果是,则忽略”(如果您只想保留第一票)。
I would create a separate table called user_post that would have the user_id and post_id - in fact, you can make those columns a multi-column primary key.
When a user votes on a post, you can use the following query:
Replace is essentially saying 'insert unless there is a unique key conflict, if so, update the row'. Or, you can use:
which essentially says 'insert unless there is a unique key conflict, if so, ignore' (if you only want to keep the first vote).