如何在日期为字符串时查询日期表

时间:2017-05-15 15:52:19

标签: php laravel laravel-5

使用accepted answer here,我想根据created_at返回所有对象。

$projects = [ {id => 1,..., 'created_at' => "2017-05-15 14:46:32",...}, ]

$time = strtotime('2017-05-15'); // format issue?

$newformat = date('Y-m-d',$time); // "2017-05-15"

$projects = $user->projects->where('created_at', $newformat);

我找回$projects的空数组,在tinker中也是如此。是的,雄辩是完美的。我是以正确的方式去做的吗?

由于我在这里,我需要使用$from查询两个日期,即$towhereBetween

$projects = $user->projects->whereBetween('created_at', [$from, $to])->toArray();

我无法记住我从哪里看到whereBetween,但却给了我错误: $from$to$newformat类似。

  

方法whereBetween不存在。

2 个答案:

答案 0 :(得分:3)

您需要指定projects作为方法,而不是属性:

$projects = $user->projects()->where('created_at', $newformat)->get();

尝试在没有$user->projects的情况下访问()将返回Collection,其中没有whereBetween方法。你必须使用:

$user->projects()->whereBetween('created_at', [$from, $to])->get();

在那种情况下。请注意Collections有一个where方法,但它与Eloquent的方法不同。

https://laravel.com/docs/5.4/collections#method-where

如果您想查询日期,我发现最好使用whereRaw()

$user->project()->whereRaw("DATE_FORMAT(`created_at`, '%Y-%m-%d') BETWEEN '".$from."' AND '".$to."'");

如果只询问一个日期:

$user->project()->whereRaw("DATE_FORMAT(`created_at`, '%Y-%m-%d') = '".$newFormat."'");

我还应该补充说,有一个whereDate()条款作为上述的简写:

https://laravel.com/docs/5.4/queries#where-clauses

$user->projects()->whereDate("created_at", $newFormat)

还有whereYear()whereMonth()whereDay(),可以将其链接起来搜索特定日期。

答案 1 :(得分:1)

你应该尝试:

$newformat = date('Y-m-d',$time).'%'; // "2017-05-15"

$projects = $user->projects()->where('created_at', 'like', $newformat);