gia*_*our 2 php laravel eloquent laravel-4
使用Laravel查询构建器针对具有日期列的表编写查询时,应使用哪种数据类型?以下应返回13个结果,但不返回任何内容:
$date = new \DateTime("-2 days");
Model::whereDate($date)->get();
Run Code Online (Sandbox Code Playgroud)
转储查询显示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)
}
Run Code Online (Sandbox Code Playgroud)
编写查询Model::whereDate($date->format("Y-m-d"))->get()
相反有效,但似乎不像Laravel那样做.
是否有特定的对象类型我应该传递给查询以按日期列过滤?
编辑:此示例中的模型如下所示:
class Model extends Eloquent {
protected $table = 'table';
public function getDates() {
return array('date');
}
}
Run Code Online (Sandbox Code Playgroud)
它引用的表看起来像这样:
CREATE TABLE table(
some_field VARCHAR(255),
date DATE
) ENGINE = 'InnoDB';
Run Code Online (Sandbox Code Playgroud)
Laravel认为date列是一个字符串:Model::lists('date')
返回一个字符串数组,就像这样DB::table('table')->lists('date')
.
更改$date = new \DateTime("-2 days");
为$date = \Carbon\Carbon::now()->subDays(2)
不允许我date
直接使用Carbon对象查询列.
更新:无论出于何种原因,内置的MySQL date
到\Carbon\Carbon
是不是为我工作,所以最简单的解决办法是写一个作为查询范围:
public function scopeDate($query, \Carbon\Carbon $date) {
return $query->whereDate($date->toDateString());
}
Run Code Online (Sandbox Code Playgroud)
您应该在getDates()数组中添加列.通过这样做,Eloquent会自动将您的日期时间转换为Carbon对象.
来自文档:
默认情况下,Eloquent会将created_at,updated_at和deleted_at列转换为Carbon实例,后者提供各种有用的方法,并扩展本机PHP DateTime类.
请参阅:http: //laravel.com/docs/eloquent#date-mutators
同样,以正确的格式(Ymd)提供日期可能仍然是必要的,因为并不总是可以告诉如何解释给定的日期