Laravel - 按月模型过滤日期字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49194573/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:29:45  来源:igfitidea点击:

Laravel - Model filter date field by month

phplaravellaravel-5php-7php-5.5

提问by edica

I have a method that can receive a parameter of "month"and another of "year", you can receive both or only one of them.

我有一个方法可以接收一个"month"参数和另一个"year" 参数,你可以同时接收它们,也可以只接收其中一个。

In the case of only receiving the monthI want to make a query that I look for in a field that is called "created_at"just looking for the monthof that field date

只接收月份的情况下,我想在一个名为“created_at”的字段中进行查询,只查找该字段日期的月份

At the moment I use this code but when doing a like it does not do it correctly

目前我使用此代码,但是在执行类似操作时它没有正确执行

        else if ($request->has('month')) {
        $month = $request->input('month');
        $currentTimestamp = date_create_from_format('n', $month)->getTimestamp();
        $currentDate = date('m', $currentTimestamp);
        $filters['updated_at'] = $currentDate;
        unset($filters['month']);
    }

        $cars = Car::where(function($query) use($filters) {
        foreach ($filters as $column => $value) {
            if ($column === 'updated_at') {
                $query->where($column, 'LIKE', '%'.$value.'%');
                continue;
            }
            $query->where($column, 'LIKE', '%'.$value.'%');
        }
    })->orderBy('updated_at', 'desc')->get();

回答by Alex

You can use whereMonthmethod, like this:

您可以使用whereMonth方法,如下所示:

$cars = Car::whereMonth('created_at', '12')->get();

Example with determining if a month value is exist:

确定月份值是否存在的示例:

if ($request->has('month')) {
   $cars = Car::whereMonth('created_at', $request->input('month'))->get();
}

回答by AddWeb Solution Pvt Ltd

You should try this:

你应该试试这个:

if ($request->has('month')) {
   $month = $request->input('month');
   Car::whereRaw('MONTH(created_at) = '.$month)->get();
}

回答by Dionisis K

You can use laravel queryBuilder.
The idea is pretty simple. Build your query and execute it only when needed

您可以使用 laravel queryBuilder
这个想法很简单。构建您的查询并仅在需要时执行它

carQuery = Car::newQuery();
if ($request->has('month') {
   carQuery->where('created_at' .. do camparison you want);
}
if ( $request->has('year') {
   // add extra query filter
}
cars = carQuery->get();