I propose two solutions, one a bit different from what you've been trying and the other more alike.
Please read/watch this references:
- https://laravel.com/docs/9.x/eloquent-relationships#other-aggregate-functions
- https://laracasts.com/series/mysql-database-design/episodes/6
- https://laracasts.com/series/mysql-database-design/episodes/8
Solution 1
class Resource extends Model
{
// add a has many relation to the pivot table
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
$requirements = Resource::query()
->withSum('requirements', 'quantity_needed') // use withSum
->findMany([2, 3]);
Solution 2
// as we are grouping by resource_id, we will get 2 records back,
// as they were aggregated to sum `quantity_needed`
$requirements = Requirement::query()
->with(['resource'])
->select([
'resource_id',
DB::raw('SUM(quantity_needed) AS quantity_needed'),
])
->groupBy('resource_id')
->findMany([1, 2, 3]);
The
Those two Resources: