【问题标题】:Date compare Eloquent 'where' method doesn't work日期比较 Eloquent 'where' 方法不起作用
【发布时间】:2016-12-26 13:54:27
【问题描述】:

我正在拼命地尝试对 SQL 请求进行排序:

我希望每一行的日期属性都小于实际日期。

这是我正在做的事情:

$student = User::find($id)->student;
$extras = $student->extras->where('find', 1)
                          ->where('date', '<', Carbon::now()->toDateString());

它返回一个空集合。这很奇怪,因为$student-&gt;extras-&gt;where('find', 1) 返回这个:

Collection {#229 ▼
  #items: array:1 [▼
    0 => Extra {#236 ▼
      #fillable: array:10 [▶]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:14 [▼
        "id" => 4
        "broadcast" => 0
        "type" => "Cuisine"
        "date" => "2016-06-15"
        "date_time" => "13:00:00"
        "duration" => 2
        "salary" => 500
        "benefits" => "test2"
        "requirements" => "test2"
        "informations" => ""
        "find" => 1
        "professional_id" => 2
        "created_at" => "2016-08-19 08:18:59"
        "updated_at" => "2016-08-19 08:18:59"
      ]

如您所见,日期远小于返回此值的Carbon::now()-&gt;toDateString()

2016-08-19

任何想法我做错了什么?

【问题讨论】:

    标签: sql laravel eloquent php-carbon


    【解决方案1】:

    您正在尝试将日期与字符串进行比较。试试这个:

    ->where('date', '<', Carbon::now());
    

    【讨论】:

      【解决方案2】:

      请记住,当您使用属性(例如 $student-&gt;extras)访问关系时,结果已经从数据库中提取,并且您使用 Illuminate\Database\Eloquent\Collection 类来过滤数据。 https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php#L282

      如果你想让数据库查询结果你需要使用你的关系的方法。 $student-&gt;extras()-&gt;where('find', 1)-&gt;where('date', '&lt;', Carbon::now())-&gt;get(); 另请注意,我没有在 carbon 对象上调用 -&gt;toDateString() 方法,通过这样做,查询生成器会将日期转换为您的数据库平台所需的正确格式。

      编辑:

      如果您真的想使用该集合来处理此问题,您需要执行以下操作

      $extras = $student->extras->filter(function($extra)
      {
          return $extra->date->lt(Carbon::now());
      });
      

      【讨论】:

      • 谢谢先生! $student->extras()->where('find', 1)->where('date', 'get();完全有效(使用 get())
      • 刚刚发现-&gt;get() 并添加了:)
      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多