我有列「exp_date」與字符串的類型,列的格式是d.m.Y. 我想在兩個日期之間得到記錄。日期格式之間的雄辯模型d.m.Y
我試圖像這樣的代碼:
$start = '10.09.2016';
$end = '20.10.2018';
$company->records()->whereBetween('exp_date', [$start, $end])->get();
我有列「exp_date」與字符串的類型,列的格式是d.m.Y. 我想在兩個日期之間得到記錄。日期格式之間的雄辯模型d.m.Y
我試圖像這樣的代碼:
$start = '10.09.2016';
$end = '20.10.2018';
$company->records()->whereBetween('exp_date', [$start, $end])->get();
只需使用carbon package它擴展了本機PHP DateTime類。
實施例1:數據庫列類型設置爲date
OR dateTime
$開始= '10 .09.2016' ; $ end = '20.10.2018';
$start = Carbon::createFromFormat('d-m-Y', $start)->toDateTimeString();
$end = Carbon::createFromFormat('d-m-Y', $end)->toDateTimeString();
然後創建查詢
$company = Records::where(function($q){
$q->where('exp_date', '<=',$start);
$q->where('exp_date', '>', $end);
});
$company->get();
例2:數據庫列類型設置爲varchar
在這裏,你將必須通過遷移所有隱蔽現有表列第一。 在修改列之前,請確保將doctrine/dbal
依賴項添加到您的composer.json
文件中。
php artisan make:migration update_exp_to_records_table --table=records
編輯遷移文件,下面有關添加到您的表名
Schema::table('records', function ($table) {
$table->string('expire')->date()->change();
});
運行僅此特定遷移 然後在你的控制器函數中使用例如1以上。
隨着原始查詢你應該使用這樣的事情:
SELECT * FROM table_name
WHERE UNIX_TIMESTAMP(col_name) > UNIX_TIMESTAMP(:start)
AND UNIX_TIMESTAMP(col_name) < UNIX_TIMESTAMP(:end)
您不必使用UNIX_TIMESTAMP()
爲$start
和$end
值與MySQL中只有strtotime()
在PHP中。
注意:如果MySQL不把你的字符串輸入到Unix時間戳,也許你需要使用函數CAST()
。
可能重複[Laravel $ q->日期之間的()()(http://stackoverflow.com/questions/24824624/laravel-q-where-between-dates) – maiorano84
@ maiorano84不完全像[Laravel $ q-> where()之間的日期] http://stackoverflow.com/questions/24824624/laravel-q-where-between-dates –