我正在写一个图像投票竞赛的应用程序。我是一个新手,这种基于ajax的动态页面。我有关于如何使它正确的问题,因为这是我的第一次尝试,我需要一些基于性能的问题的答案。我可以添加选票,但我不能获得图像的总票数。因此,我对性能感到困惑,因为所有用户都可以同时投票。如何才能显示每个图像的总票数。我的数据库表在下面的第二个问题中。
我为每个图片添加了一个投票按钮:
<button type="submit" class="btn btn-mini upvote newsbutton" id="{{ $contestimage->id }}">
<i class="fa fa-thumbs-up fa-2x"></i>
</button>
<div id="voteresponse"></div>并使用ajax将表单发送到路由:
$('.upvote').click( function(event) {
event.preventDefault();
$("#voteresponse").html('');
var voteID = $(this).attr("id");
$.ajax({
url: "voteimage",
type: "post",
dataType: "json",
data: {id : voteID},
success: function(data, textStatus){
if(data.success == 'true'){
$('#voteresponse').html(data.message);
return true;
}else{
$('#voteresponse').popover({
title: 'Hata!',
content: data.message
});
}
},
error:function(){
$('#voteresponse').popover({
title: 'error!',
content: 'Server error'
});
}
});
});我的控制器动作是
public function postVote($id = null)
{
if (Sentry::check()) {
if (Request::ajax())
{
$id=Input::get('contestImageId');
$image = ContestImage::find($id);
$vote = "1";
$user = Sentry::getUser()->id;
// Grab the vote if it already exists.
$entry = Vote::where('user_id', $user)->where('contest_id', $image)->first();
if (!empty($entry))
{
$entry->vote = $vote;
$entry->save();
}
else
{
$entry = new Vote;
$entry->user_id = $user;
$entry->contest_id = $image->id;
$entry->vote ="1";
$entry->save();
}
}
else
{
return "Not an AJAX request.";
}
}
else
{
return "User not logged in.";
}
}代码可以工作,但我被困在这一点上。我不知道如何返回总投票计数,以及所有其他ajax页面,当任何其他用户投票时,我如何添加脚本来刷新votecount ?这会造成任何性能问题吗?
第二个问题与第一个问题相关:我在数据库中创建了我的选票迁移和收集
user_id(int)
contestimage_id(int)
vote(tinyinteger to use as 1)我有一个belongsTo和hasMany的关系,我想用$contestimage->votes()->count();来计算总票数,这是计算选票的好方法吗?
发布于 2014-03-24 23:32:11
你应该写一个计算投票数量的函数,查看this页面上的“原始表达式”,这应该会对你有帮助。您可以使用MySql count(*)来计算行数。
使用该函数,在页面上显示投票数,然后在成功运行postVote函数后让它返回总票数。
$entry = new Vote;
$entry->user_id = $user;
$entry->contest_id = $image->id;
$entry->vote ="1";
$entry->save();
// RETURN NUMBER OF VOTES HERE然后让返回的数字更新包含总票数的div
if(data.success == 'true'){
$('#voteresponse').html(data.message);
$('#totalvotes').html(data.totalvotes);
return true;https://stackoverflow.com/questions/21636264
复制相似问题