如何在Laravel中使用Eloquent比较日期?

时间:2015-06-13 06:54:19

标签: laravel laravel-5

当我运行此代码时,

$entry_id = Entry::where(function($q)use($intern,$input){
                    $q->where('interna_id',$intern['id']);
                    $q->where('created_at','=','2015-06-06');
                })->first(['id']);

它给出了

select `id` from `entries` where (`interna_id` = 1 and `created_at` = 2015-06-06) limit 1

如您所见,日期未包含在''中。这会导致问题,MySQL将无法找到记录。例如,如果我添加'',就像这样,

select `id` from `entries` where (`interna_id` = 1 and `created_at` = '2015-06-06') limit 1 

查询能够检索正确的记录。

注意:created_at使用的是日期格式,而不是DateTime

1 个答案:

答案 0 :(得分:0)

created_at是laravel的日期类型。它使用Carbon包并期望这样的对象。你必须做类似的事情:

$entry_id = Entry::where(function($q)use($intern,$input){
                    $q->where('interna_id',$intern['id']);
                    $q->where('created_at','=', Carbon::parse('2015-06-06'));
                })->first(['id']);

请注意,您必须使用;

在页面上包含库

使用Carbon \ Carbon; enter code here

或者您也可以使用DB::raw作为日期(未经测试):

$entry_id = Entry::where(function($q)use($intern,$input){
                    $q->where('interna_id',$intern['id']);
                    $q->where('created_at','=', \DB::raw('2015-06-06'));
                })->first(['id']);