finlamit
2 months ago

Eloquent, group by relationship.

Posted 2 months ago by finlamit

Hi

My data.

Projects  -> (has many) Tasks -> (has many) SubTasks

I am looking to display all of the SubTasks in order of the SubTask 'due_date' column, grouped by the project they belong to.

The page would then display something like this:

Project B
	Task 2
		Sub Task One (due 1st Sep)
		Sub Task Three (due 2nd Sep)
	Task 1
		Sub Task Two (due 3rd Sep)

Project A
	Task 1
		Sub Task Two (due 4th Sep)

Project B <---- repeated
	Task C
		Sub Task 2 (due 5th Sep)


Project A  <-- repeated
	Task 1 <-- repeated
		Sub Task 1 (due 6th Sep)

Any ideas?? Completly stumped. I have got this far:

$subtasks = SubTask::with(['task.project' => function ($query) {
            $query->groupBy('id');
       }])->orderBy('due_date')->get();

Which retrieves the data but I need to go 2 steps further grouping them by Tasks and then by Project.

Thanks in advace!

Please sign in or create an account to participate in this conversation.