【问题标题】:Laravel Collection Get method not working as expectedLaravel Collection Get 方法未按预期工作
【发布时间】:2016-04-14 11:22:29
【问题描述】:

我在 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?

【问题讨论】:

  • 试试$contract->where('day_of_wk', 1)->all()->get('start_time');

标签: php laravel-5.1 laravel-collection


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2021-05-22
  • 2016-11-17
  • 2015-09-26
  • 2014-04-03
  • 2019-04-22
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多