我有一个可以接收"月">参数和另一个"年">参数的方法,您可以同时接收或仅接收其中一个。
在只收到月份的情况下,我想在名为"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();
你应该试试这个:
if ($request->has('month')) {
$month = $request->input('month');
Car::whereRaw('MONTH(created_at) = '.$month)->get();
}
您可以使用 whereMonth 方法,如下所示:
$cars = Car::whereMonth('created_at', '12')->get();
确定月份值是否存在的示例:
if ($request->has('month')) {
$cars = Car::whereMonth('created_at', $request->input('month'))->get();
}
您可以使用 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();