2014-02-07 61 views
0

我正在爲圖像投票比賽撰寫應用程序。我是這種基於Ajax的動態頁面的新手。我有關於如何正確設置的問題,因爲這是我的第一次嘗試,我需要一些基於性能的問題的答案。我可以添加投票,但是,我無法獲得圖像的總票數。因此,我的思想對性能感到困惑,因爲所有的用戶都可以同時投票。如何顯示每張圖片的總投票數。我的數據庫表在第二個問題下面。動態Laravel/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."; 
     } 
    } 

代碼工作,但我堅持在這一點上。我不能計算如何發回總票數和所有其他阿賈克斯頁ho w我可以添加一個腳本來刷新votecount當其他用戶投票嗎?這是否會造成任何性能問題?

第二個問題與第一個問題相關:我創造了我的票遷移和在數據庫收集

user_id(int) 
contestimage_id(int) 
vote(tinyinteger to use as 1) 

我有票,contestimages之間屬於關聯和的hasMany關係,我想用$contestimage->votes()->count();是獲得總計數這是一個很好的選擇來計算投票?

回答

1

你應該寫一個函數來計算投票數,在this頁簽出'Raw Expressions',這應該可以幫助你。您可以使用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;