当使用 Laravel 查询生成器针对包含日期列的表编写查询时,应使用哪种数据类型?以下应该返回 13 个结果,但实际上什么也没有返回:
$date = new \DateTime("-2 days");
Model::whereDate($date)->get();
转储查询表明 laravel 正在尝试这样做:
array(3) {
'query' =>
string(62) "select * from `table` where `date` = ?"
'bindings' =>
array(1) {
[0] =>
class DateTime#310 (3) {
public $date =>
string(19) "2013-10-07 14:39:11"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
}
'time' =>
double(5.55)
}
将查询写成 Model::whereDate($date->format("Y-m-d"))->get()
是可行的,但看起来不像 Laravel 的方式。
是否应该将特定对象类型传递到查询中以按日期列进行过滤?
编辑:本例中的模型如下所示:
class Model extends Eloquent {
protected $table = 'table';
public function getDates() {
return array('date');
}
}
它引用的表如下所示:
CREATE TABLE table(
some_field VARCHAR(255),
date DATE
) ENGINE = 'InnoDB';
Laravel 认为日期列是一个字符串:Model::lists('date')
返回一个字符串数组,DB::table('table')->列表('日期')
。
将 $date = new\DateTime("-2 days");
更改为 $date =\Carbon\Carbon::now()->subDays(2)
不允许我直接使用 Carbon 对象查询 date
列。
更新:无论出于何种原因,\Carbon\Carbon
的内置 MySQL date
对我不起作用,因此最简单的解决方案是编写一个作为查询范围:
public function scopeDate($query, \Carbon\Carbon $date) {
return $query->whereDate($date->toDateString());
}
最佳答案
您应该将您的列添加到 getDates() 数组中。通过这样做,Eloquent 会自动将您的日期时间转换为 Carbon 对象。
来自文档:
By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class.
看这个: http://laravel.com/docs/eloquent#date-mutators
同样,以正确的格式 (Y-m-d) 提供日期可能仍然是必要的,因为并不总是能够告诉如何解释给定的日期
关于php - 使用 Laravel 的查询构建器查询日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275263/