Laravel 5.1查询刀片模板内的集合

时间:2016-02-27 22:26:05

标签: php eloquent laravel-5.1 laravel-blade laravel-collection

在我的刀片模板中,我有以下$ questions集合

SELECT t1.matchId, t1.summonerId, t1.championId, t1.teamId, t1.winner
FROM mytable AS t1
LEFT JOIN mytable AS t2 
  ON t1.matchId = t2.matchId AND t1.teamId = t2.teamId AND t2.summonerId = 42999456
WHERE t1.matchId = 2528256239 AND t2.matchId IS NULL

要检查是否存在question_num,我可以执行以下操作:

Collection {
  #items: array:2 [
    0 => Question {
      ....
      #attributes: array:7 [
        "survey_id" => 3
        "question_num" => 0
        "question_text" => "test"
        "expected_answer" => 1
        "created_at" => "0000-00-00 00:00:00"
        "updated_at" => "0000-00-00 00:00:00"
      ]
    }
    1 => Question {#318 ▶}
  ]
}

但有没有办法可以做这样的事情,这样我就可以直接查询集合而不必使用循环?

 @foreach ($questions as $question) {
     @if ($question->question_num == 0)
       {{ $question->question_text }}
     @endif 
 @endforeach

应用where方法 {{ $questions->where('question_num','=', 0)->get('question_text', null) }} 会得到以下结果:

$questions->where('question_num','=', 0)

那么当我链接get方法[{"survey_id":3,"question_num":0,"question_text":"test","expected_answer":1,"created_at":"2016-02-28 14:20:17","updated_at":"2016-02-28 14:20:17"}]

时,为什么它会重新引用null

1 个答案:

答案 0 :(得分:1)

请改用first()方法。在Laravel中get()返回一个可列表的集合