0

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?

1 Answer 1

0

I 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(),
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.