So I have three models: Volunteer, Task and Payment. A Volunteer can have many (has many relationship) tasks and a task can have many (another has many relationship) payments.
class Volunteer
public function tasks()
{
return $this->hasMany(Task::class);
}
class Task
public function volunteer()
{
return $this->belongsTo(Volunteer::class);
}
public function payments()
{
return $this->hasMany(Payment::class);
}
class Payment
public function task() {
return $this->belongsTo(Task::class);
}
Now I want to query all volunteers with unpaid/ partially paid tasks. So, basically I want to filter a volunteer's tasks where each task's amount should equal the sum of all payments linked to that particular task.
I tried using whereHas and with but I don't seem to be able to filter the tasks properly.
I've managed to do it with joins but was wondering if it's possible to with whereHas or with. Below is the code:
Volunteer::select('volunteers.id', 'volunteers.name', 'tasks.amount', DB::raw('SUM(payments.amount) as amount_paid'))
->join('tasks', 'tasks.volunteer_id', '=', 'volunteers.id')
->leftJoin('payments', 'payments.task_id', '=', 'tasks.id')
->groupBy('volunteers.id', 'volunteers.name', 'tasks.amount')
->havingRaw('amount_paid >= tasks.amount')
->get();
Any help would be appreciated!