drfu80954 2015-08-10 14:56
浏览 68

使用Laravel 5建立投票系统

I'm trying to build voting system for my web page (Laravel 5). Now, any user can vote multiple times, I want to fix it.

Here is my code in php:

public function addVote()
{
    $bikepoint = $this->bikepoint->find($id);
    $userid = \Sentry::getUser()->id;
    $votesid = \DB::table('bikepoints')->select('votesuid')->where('votesuid', 'LIKE' , $userid)->get();
    if (...) {
        $bikepoint->votes = $bikepoint->votes + 1;
        $bikepoint->votesuid = $bikepoint->votesuid . $userid . '; ';
        echo 'Success!';
    }
    else {
        echo 'Fail!';
    }
    $bikepoint->save();
}

My DB table:

id  title   votes  votesuid
1   point1  2      93; 22;
2   point2  3      92; 28; 47;
3   point3  45     ...
4   point4  32     ...
5   point5  12     ...

So when user click the "Add vote" button, a function adds its ID to the votesuid field and one vote to the votes field.

I want to check if the user has already voted by checking if his ID is placed in the votesuid field. And, if so, the user cannot vote anymore.

For example, users with IDs 92, 28 and 47 should not be able to vote another time.

  • 写回答

1条回答 默认 最新

  • dongtiran7769 2015-08-12 15:59
    关注

    As suggested by others in the comments, yes, you do need to change your system so that each vote has it's own record on a table.

    So create a Votes table and a Laravel model class for it, and give your Users model class a hasMany() relationship to Votes.

    That's actually not too much work, is it?

    But now then the solution to your question becomes trivially easy -- ie:

    $votes = Sentry::getUser()->votes;
    

    As things stand, you would need to do sub-string LIKE queries, which are much harder to write, and will also give you major performance problems when your DB starts getting bigger, so yes, you definitely need to be refactoring it now.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题