I have in laravel a model called cropGathering that has a hasMany relationship with cropGatheringTransaction. The latter has a tons attribute, so what I need is to fetch all the cropGatherings, where the sum of the tons of their transactions is greater than 0.
In the cropGathering model I have the relationship:
public function cropGatheringTransactions()
{
return $this->hasMany(CropGatheringTransaction::class);
}
What I tried and had no success was the following:
public function all($perPage, $orderBy = 'id', $order = 'desc')
{
return CropGathering::whereHas('cropGatheringTransactions', function ($q) {
$q->groupBy('crop_gathering_transaction.id')
->havingRaw('SUM(crop_gathering_transaction.tons) > 0');
})
->orderBy($orderBy, $order)
->paginate($perPage);
}
I also tried the following, I defined in the cropGathering model an append:
protected $appends = ['tons'];
where I get the sum of their transactions:
public function getTonsAttribute()
{
return $this->cropGatheringTransactions()->sum('tons');
}
And when testing:
CropGathering::sum('tons', '>', 0)
tells me:
Undefined column: 7 ERROR: column \"tons\" does not exist
Should have:
select
that takes at least the oneid
from the table to be able to group laterselectRaw
we write the aggregation function to sum the columntons
id
so we make sure that the records that match this value are merged into a single rowhavingRaw
to filter by the alias that we gave to the aggregation function, which is Total (remember that if the value to compare comes from an aggregation function, then we will useHAVING
)select
that column in it.Regarding the issue of pagination, you should check the doc. official , since it mentions that pagination operations on results that require a
groupBy()