the easiest would be to look at the generated SQL and run an explain plan on it. My guess is that you probably need an index or two.
How can i improve query in Laravel for few milions records?
Hello everyone, I have a question regarding the Laravel query builder. I have a task where I need to retrieve only those purchasegroups from the Purchase model that have a pricelist with ordered set to true and at the same time do not have any pricelist with tax set to null. I return the data through a cron job to the log. The problem, however, is that even after 63 minutes, which is the longest cron I have, the data still doesn't get logged simultaneously. It also happens that a purchase is logged despite the query settings specifying that the pricelist should have ordered as false or tax as null. But main task is, log finally just purchases which hase purchasegroup with pricelists that have differnt tax inside one purchase..For example Purchae has 3 purchasegroups and every purchase group has its own pricelist but every pricelist must have tax = 19 ˇ%, they cant have different taxes inside one purchase..Can someone please try to advise me?
This is my code in cron file which is filtering data.
public function handlePurchases()
{
Log::info('Cron started');
$purchaseGroupQuery = Purchasegroup::whereHas('purchase')
->whereHas('pricelist', function ($query) {
$query->where('ordered', '=' ,true)->where('tax', '!=', null);
})
->with([
'pricelist' => function ($query) {
$query->selectRaw("REPLACE(
REPLACE('tax', ',', ''), '.', ''
) as formatted_tax")
->groupBy('formatted_tax');
}
]);
$printedPurchases = [];
$purchaseGroupQuery->chunk(1000, function ($chunks) use (&$printedPurchases) {
foreach ($chunks as $purchaseGroup) {
$purchaseGroupId = $purchaseGroup->purchase;
if (!in_array($purchaseGroupId, $printedPurchases)) {
$purchaseGroupTaxes = $purchaseGroup->pricelists->pluck('tax')->filter(function ($tax) {
return $tax !== null;
});
if ($purchaseGroupTaxes->isNotEmpty()) {
Log::info("purchase: {$purchaseGroupId}", $purchaseGroupTaxes->toArray());
}
$printedPurchases[] = $purchaseGroupId;
}
}
});
Log::info('Cron Ended');
}
This is relation in Purchase model
public function purchasegroups()
{
return $this->hasMany(Purchasegroup::class, 'purchase');
}
Relations in Purchasegroup model
public function purchase()
{
return $this->belongsTo(Purchase::class, 'purchase');
}
public function pricelists()
{
return $this->hasMany(Pricelist::class, 'purchasegroup','id');
}
public function pricelist()
{
return $this->hasOne(Pricelist::class, 'purchasegroup','id')->where("ordered", true);
}
And relation in Pricelist model
public function purchasegroup()
{
return $this->belongsTo(Purchasegroup::class, 'purchasegroup');
}
I will be glad for every advice!
Please or to participate in this conversation.