Laravel Collection获取方法无法按预期工作

时间:2016-01-09 22:32:03

标签: php laravel-5.1 laravel-collection

我在php artisan tinker中试过以下内容:

  >>>  $contract = \App\ContractHour::where('user_id', '=', 14)->get();
  =>  Illuminate\Database\Eloquent\Collection {#747
        all: [...]
      }

  >>>  $contract->where('day_of_wk', 1);
  => Illuminate\Database\Eloquent\Collection {#719
       all: [
         App\ContractHour {#726
           user_id: 14,
           day_of_wk: 1,
           start_time: "09:00:00",
           end_time: "05:00:00",
           break_time: "01:00:00",
           created_at: "2016-01-09 17:49:22",
           updated_at: "2016-01-09 17:49:22",
         },
       ],
     }
  >>> $contract->where('day_of_wk', 1)->get('start_time');
  => null

为什么当start_time存在时,get方法返回null?

1 个答案:

答案 0 :(得分:1)

您正在错误地使用get()方法。 它的作用是返回一个集合,如果您只需要一个符合条件的项目,那么请尝试使用first()代替。

$contract->where('day_of_wk', 1)->first()->start_time; //outputs 09:00:00