I'm building application with Laravel, Inertiajs and Vue3. There are three key tables in application: Operators, Locations and Terminals. Terminals belongs to Locations and Locations belongs to Operators. There is no direct relations between Operators and Terminals. I would like to display list of Operators with counting locations and counting their terminals.
For example. Operator John Doe have 3 locations. Every his location have 3 terminals. Result should be:
John Doe | 3 | 9
something like this:
$operators = Operator::countWith('locations')->countWith('locations.terminals')->get()
Of course, this doesn't work, but is there some similar options to get this counts?
I'm building application with Laravel, Inertiajs and Vue3. There are three key tables in application: Operators, Locations and Terminals. Terminals belongs to Locations and Locations belongs to Operators. There is no direct relations between Operators and Terminals. I would like to display list of Operators with counting locations and counting their terminals.
For example. Operator John Doe have 3 locations. Every his location have 3 terminals. Result should be:
John Doe | 3 | 9
something like this:
$operators = Operator::countWith('locations')->countWith('locations.terminals')->get()
Of course, this doesn't work, but is there some similar options to get this counts?
Share Improve this question edited Feb 7 at 20:45 kissu 46.7k16 gold badges89 silver badges186 bronze badges asked Feb 7 at 20:39 Mirsad BatilovicMirsad Batilovic 4411 gold badge5 silver badges18 bronze badges1 Answer
Reset to default 0I find solution in Laravel documentation eloquent relationships hasManyThrough
In Operator Model I create terminals method
public function terminals(): HasManyThrough {
return $this->hasManyThrough(Terminal::class, Location::class);
}
and in OperatorController index method
public function index() {
$operators = Operator::withCount('locations')->withCount('terminals')->get();
return Inertia::render('Operator/Index', [
'operators' => OperatorResource::collection($operators)
]);
}
In OperatorResource toArray method
public function toArray(Request $request): array {
return [
'id' => $this->id,
'name' => $this->name,
'locations_count' => $this->locations->count(),
'terminals_count' => $this->terminals->count(),
];
}