简体   繁体   中英

Laravel Eloquent Select Between current month and previous 3 months

i'm trying to build a query that will select all of the records in my DB between now (current month) and the previous 3 months.

My query somewhat works, but i want to ignore the day of the month. At the moment, it's selecting the last # of months to the current DAY as well but i want to ignore the current day and use the start and end of the months.

Here's my query:

$dateS = Carbon::now()->subMonth(3);
$dateE = Carbon::now(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

Any help would be appreciated. It's really bugging me!

This will do the trick I guess

$dateS = Carbon::now()->startOfMonth()->subMonth(3);
$dateE = Carbon::now()->startOfMonth(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

startOfMonth() begins with 1st date of the month

Use Carbon:

$data = Data::where("created_at",">", Carbon::now()->subMonths(6))->get();

You need to import the namespace to use Carbon:

use Carbon\Carbon;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM