Laravel - 查询最后两个等于的位置

时间:2016-09-26 14:53:56

标签: php mysql laravel eloquent

我需要进行查询,我需要检查最后两行是否有answered列等于字符串'not'。这是我的控制器中if循环的条件:

$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,
                    ],
                    []
                ));
            }

但它没有像我预期的那样工作,因为即使不应该输入if循环也是如此。

2 个答案:

答案 0 :(得分:1)

你犯了一个很小的错误

$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

答案 1 :(得分: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,
                    ],
                    []
                ));
            }