最近偶然發(fā)現(xiàn)有人在Stack Overflow提到Laravel檢索日期的時(shí)候,最好使用WhereBetween 而不是WhereDate所计,于是實(shí)地做了測(cè)試,非常明顯。
use App\Models\Ticket;
use Carbon\Carbon;
$now=Carbon::now();
//query in 6 million rows.
Ticket::whereDate('created_at',$now->toDateString())->count(); //1.2 sec
Ticket::WhereBetween('created_at',[
$now->startOfDay(),
$now->endOfDay()
])->count(); //0.04sec
顯而易見(jiàn)痘系,對(duì)時(shí)間區(qū)間進(jìn)行查詢的時(shí)候,最好直接對(duì)比區(qū)間值饿自,where 'created_at' between
的效率比where date('created_at')
優(yōu)秀兩個(gè)數(shù)量級(jí)汰翠。