[英]Laravel Eloquent returning empty when using date in where clause
我有简单的模型Archive,它与MySQL表紧密相关。 表格具有日期类型的字段日期,以及其他一些字段,例如ID,标题,描述等。
如果通过除日期以外的任何其他字段进行查询,我将获得所有期望的结果。 到目前为止,模型仅返回空结果。
$criteria = array(['prog_i','=',9], ['date','>=','2017-11-01'], ['date','<=','2017-11-11']);
$offset = 0;
$query = Archive::where($criteria)
->orderBy('date', 'desc')
->skip($offset)
->take(40);
$results = $query->get();
var_dump($results);
/* object(Illuminate\Database\Eloquent\Collection)#350 (1) { ["items":protected]=> array(0) { } }
*/
但是,如果我使用phpMyAdmin中由Laravel(来自调试器)构建的相同查询进行测试,则它可以很好地工作并返回结果。
select * from `archive` where (`prog_id` = '9' and `date` >= '2017-11-01' and `date` <= '2017-11-11') order by `date` desc limit 40 offset 0
Showing rows 0 - -1 (4 total, Query took 0.3204 seconds.)
有什么可能是错的吗?
您可以尝试whereDate
$criteria = array(['prog_id','=',9]);
$criteria_1 = array(['date','>=','2017-11-01'], ['date','<=','2017-11-11']);
$offset = 0;
$query = Archive::where($criteria)
->whereDate($criteria_1)
->orderBy('date', 'desc')
->skip($offset)
->take(40)
->toSql();<--- add toSql for check your query
print_r($query);
你应该用
$query = Archive::where('prog_id','=',9)
->whereBetween('date',['2017-11-01','2017-11-11'])
->orderBy('date', 'desc')
->skip($offset)
->take(40);
您不能在多个位置传递数组,但是可以在内部通过循环传递条件。
$query = Archive::query();
foreach($criteria as $item) {
$query->where($item[0], $item[1], $item[2]);
}
$query->orderBy('date', 'desc')
->skip($offset)
->take(40);
$results = $query->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.