dongliang1996 2018-03-09 05:11
浏览 23
已采纳

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

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

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

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();
  • 写回答

3条回答 默认 最新

  • doru52911 2018-03-09 22:41
    关注

    You should try this:

    if ($request->has('month')) {
       $month = $request->input('month');
       Car::whereRaw('MONTH(created_at) = '.$month)->get();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部