日期比较 Eloquent 'where' 方法不起作用
Date compare Eloquent 'where' method doesn't work
我正拼命地尝试对 SQL 请求进行排序:
我想要日期属性小于实际日期的每一行。
这是我正在做的事情:
$student = User::find($id)->student;
$extras = $student->extras->where('find', 1)
->where('date', '<', Carbon::now()->toDateString());
它 returns 一个空的集合。这很奇怪,因为 $student->extras->where('find', 1)
returns 这个 :
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()->toDateString()
returns 这个值:
2016-08-19
知道我做错了什么吗?
您正在尝试将日期与字符串进行比较。试试这个:
->where('date', '<', Carbon::now());
请记住,当您使用 属性(例如 $student->extras
)访问关系时,结果已经从数据库中提取并且您使用 Illuminate\Database\Eloquent\Collection
class过滤数据。 https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php#L282
如果你想让数据库查询结果你需要使用你的关系的方法。 $student->extras()->where('find', 1)->where('date', '<', Carbon::now())->get();
另请注意,我没有在 carbon 对象上调用 ->toDateString()
方法,通过执行此操作,查询构建器会将日期转换为您的数据库平台所需的正确格式。
编辑:
如果您真的想使用集合来处理这个问题,您需要执行以下操作
$extras = $student->extras->filter(function($extra)
{
return $extra->date->lt(Carbon::now());
});
我正拼命地尝试对 SQL 请求进行排序:
我想要日期属性小于实际日期的每一行。
这是我正在做的事情:
$student = User::find($id)->student;
$extras = $student->extras->where('find', 1)
->where('date', '<', Carbon::now()->toDateString());
它 returns 一个空的集合。这很奇怪,因为 $student->extras->where('find', 1)
returns 这个 :
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()->toDateString()
returns 这个值:
2016-08-19
知道我做错了什么吗?
您正在尝试将日期与字符串进行比较。试试这个:
->where('date', '<', Carbon::now());
请记住,当您使用 属性(例如 $student->extras
)访问关系时,结果已经从数据库中提取并且您使用 Illuminate\Database\Eloquent\Collection
class过滤数据。 https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php#L282
如果你想让数据库查询结果你需要使用你的关系的方法。 $student->extras()->where('find', 1)->where('date', '<', Carbon::now())->get();
另请注意,我没有在 carbon 对象上调用 ->toDateString()
方法,通过执行此操作,查询构建器会将日期转换为您的数据库平台所需的正确格式。
编辑:
如果您真的想使用集合来处理这个问题,您需要执行以下操作
$extras = $student->extras->filter(function($extra)
{
return $extra->date->lt(Carbon::now());
});