php 来自数据库的两个日期之间的 Laravel 5 和 Eloquent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41101474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 and Eloquent between two dates from database
提问by V? H?ng
I am a beginner with Laravel 5. I have a table: users with columns CreateDate, Type and Channel.
我是 Laravel 5 的初学者。我有一个表:包含 CreateDate、Type 和 Channel 列的用户。
I have a list with users and I choose in View: Trans StartDate, Trans EndDate, Type and Channel.
我有一个用户列表,我在视图中选择:Trans StartDate、Trans EndDate、Type 和 Channel。
I want to show: Tras StartDate < CreateDate < Trans EndDate
with Type and Channel. name="time_start", "time_end", "type", "channel"
.
我想展示:StartDate < CreateDate < Trans EndDate
带有类型和频道的Tras 。name="time_start", "time_end", "type", "channel"
.
My Route:
我的路线:
Route::post('user', 'CSKHController@index');
My Controller:
我的控制器:
public function index() {
$start = Input::get ( 'time_start' );
$end = Input::get ( 'time_end' );
$articles = KhachHang::all()->whereBetween('CreateDate', [$start, $end])->get();
return view('admin/layouts/test', compact('stt','article'))->withDetails($articles);
}
Help me please!
请帮帮我!
回答by chebaby
Laravel 5.*
Laravel 5.*
This is an example of how i used eloquent between in a laravel 5.6project.
这是我如何在laravel 5.6项目中使用 eloquent 的示例。
my-view.blade.php
我的view.blade.php
simplified html form:
简化的 html 形式:
<form action="my-route" method="POST">
{{ csrf_field() }}
<input type="date" name="from">
<input type="date" name="to">
<button type="submit">Submit</button>
</form>
MyController.php
我的控制器.php
use Illuminate\Support\Carbon;
// ...
$request->validate([
'from' => 'required|date',
'to' => 'required|date',
]);
$from = Carbon::parse($request->from)
->startOfDay() // 2018-09-29 00:00:00.000000
->toDateTimeString(); // 2018-09-29 00:00:00
$to = Carbon::parse($request->to)
->endOfDay() // 2018-09-29 23:59:59.000000
->toDateTimeString(); // 2018-09-29 23:59:59
$models = Model::whereBetween('created_at', [$from, $to])->get();
// do whatever you want with the query results...
Additional resources
其他资源
回答by Manoj
Simply do this in your laravel query.
只需在您的 Laravel 查询中执行此操作。
->whereBetween('your_field', [$from, $to])->get();
->whereBetween('your_field', [$from, $to])->get();
回答by Laerte
To check between two dates, you could use this (among other options):
要在两个日期之间进行检查,您可以使用它(以及其他选项):
$articles = KhachHang::where('CreateDate', '>=', $start)
->where('CreateDate', '<=', $end)->get();
You have to be sure that the date format is 'Y-m-d', or the code will not work.
您必须确保日期格式为“Ym-d”,否则代码将不起作用。