简体   繁体   中英

Laravel Eloquent returning empty when using date in where clause

I have simple model Archive, which is tight to MySQL table. Table has field date of type date, and some other fields, like id, title, description etc.

I'm getting all the desired results if making query by any other fields than date. When it comes to date, model just returns empty results.

$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) { } } 
*/

However if I use same query built by Laravel (from debugger) in phpMyAdmin for testing, it works perfectly fine and is returning results.

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.)

What could possibly be wrong?

You can try 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);

You should use

$query = Archive::where('prog_id','=',9)
  ->whereBetween('date',['2017-11-01','2017-11-11'])
   ->orderBy('date', 'desc')
   ->skip($offset)
    ->take(40);

You can't pass array for multiple where, but you can internally pass conditions with a loop.

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM