This is my job. When I run this job the online invoices query doesn't display anything, but what is intriguing is that when I swap the places of the $onlineInvoices and the $offlineInvoices variables the $onlineInvoices query works while the $offlineInvoices doesn't. It worked fine when I redefined the $monthlyInvoices again below the $offline_sales variable, But I would like to know why this occurs.
<?php
namespace App\Jobs;
use App\Models\Invoice;
use App\Models\InvoiceMonthlyStatistics;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class InvoiceMonthlyStatisticsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$period = CarbonPeriod::create('2021-08-18', '1 month', Carbon::now()->toDateString());
foreach ($period as $date) {
$monthlyInvoices = Invoice::
whereRaw('YEAR(created_at) = ?', $date->format('Y'))
->whereRaw('MONTH(created_at) = ?', $date->format('m'));
$total_sales = $monthlyInvoices
->sum('net_price');
$offline_sales = $monthlyInvoices
->where('type', '=', 'offline')
->sum('net_price');
$online_sales = $monthlyInvoices
->where('type', '=', 'online')
->sum('net_price');
$invoiceStats = (new InvoiceMonthlyStatistics)->create([
'total_sales' => $total_sales,
'online_sales' => $online_sales,
'offline_sales' => $offline_sales,
'month' => $date->format('m'),
'year' => $date->format('y')
]);
}
$invoiceStats->save();
}
}
Aucun commentaire:
Enregistrer un commentaire