【问题标题】:Laravel - Model filter date field by monthLaravel - 按月的模型过滤日期字段
【发布时间】:2018-08-18 01:45:30
【问题描述】:

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

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

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

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

【问题讨论】:

  • created_at 是时间戳列吗?

标签: php laravel laravel-5 php-7 php-5.5


【解决方案1】:

你应该试试这个:

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

【讨论】:

  • @edica:感谢您的支持。如果我们的解决方案解决了您的问题,请随时接受此作为答案。谢谢
【解决方案2】:

你可以使用whereMonth方法,像这样:

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

判断月份值是否存在的示例:

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

【讨论】:

  • 此答案基于 API 更实用,甚至可以回答问题:按月、年或日过滤。谢谢
【解决方案3】:

你可以使用 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();

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 2019-05-31
    • 2021-11-25
    • 2022-06-11
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多