Laravel中如何用数组调用whereMonth?能否将数组作为DB::whereMonth的参数?
whereMonth with Arrays in Laravel Hey there! Let's tackle your two questions one by one:
Question 1: How to use an array with the whereMonth method in Laravel?
The built-in whereMonth method in Laravel is designed to filter records where a date column matches a single month. To filter for multiple months using an array, you'll need to combine whereIn with a raw SQL expression to extract the month from your date column. Here's how to do it:
Example with Query Builder:
$targetMonths = [1, 2, 12]; // January, February, December $records = DB::table('your_table_name') ->whereIn(DB::raw('MONTH(created_at)'), $targetMonths) ->get();
Example with Eloquent:
If you're working with a model, the syntax is almost identical:
use App\Models\YourModel; $targetMonths = [1, 2, 12]; $records = YourModel::whereIn(DB::raw('MONTH(created_at)'), $targetMonths)->get();
The DB::raw('MONTH(created_at)') part tells the database to extract the numeric month from the created_at column, and whereIn checks if that value exists in your array of target months.
Question 2: Can I pass an array directly to whereMonth, like ->whereMonth([01, 02, 12])?
Short answer: No, you can't.
The whereMonth method's signature expects a column name, an optional operator (default is =), and a single value for the month. If you pass an array as the second argument, Laravel will interpret it as the operator—which is invalid—and throw a runtime error.
For example, writing ->whereMonth('created_at', [1,2,12]) will break your code because the method doesn't support arrays as the match value. Stick with the whereIn + DB::raw approach from Question 1 instead.
内容的提问来源于stack exchange,提问作者Karabah

