2016-09-26 49 views
0

我需要做一個查詢,我需要檢查是否最後兩行的列answered等於字符串'不'。這是在我的控制器中,如果循環條件:Laravel - 查詢最後兩個等於

$inactive = Answer::orderBy('created_at', 'desc') 
          ->where('answered', 'not') 
          ->where('player_id', $player->id) 
          ->where('quiz_id', $quiz->id) 
          ->take(2); 

if ($inactive) { 
       // The game was finished 
       $opponent = $quiz->getOpponent($player); 
       $quiz->status = 'finished'; 
       $quiz->save(); 

       Event::fire(new GameEvent(
        'quizFinished', 
        [ 
         $opponent->user, 
         $player->user, 
        ], 
        [] 
       )); 
      } 

但它不工作,我期望的,因爲如果即使它不應該是循環被輸入。

回答

0

你已經做了一個非常小的失誤

$inactive = Answer::orderBy('created_at', 'desc') 
          ->where('answered', 'not') 
          ->where('player_id', $player->id) 
          ->where('quiz_id', $quiz->id) 
          ->take(2) 
          ->get(); 

通知的->get()

沒有這個,$inactive仍然是一個雄辯的對象。這意味着它不是空的。

請參考:https://laravel.com/docs/5.1/eloquent#retrieving-multiple-models

0
$inactive = Answer::orderBy('created_at', 'desc') 
          //->where('answered', 'not') 
          ->where('player_id', $player->id) 
          ->where('quiz_id', $quiz->id) 
          ->take(2); 

if ($inactive->count() == 2 && $inactive->first()->answered == 'not' && $inactive->last()->answered == 'not') { 
       // The game was finished 
       $opponent = $quiz->getOpponent($player); 
       $quiz->status = 'finished'; 
       $quiz->save(); 

       Event::fire(new GameEvent(
        'quizFinished', 
        [ 
         $opponent->user, 
         $player->user, 
        ], 
        [] 
       )); 
      }