最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

relationship - Laravel withCount elements in related and subrealted table - Stack Overflow

programmeradmin1浏览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?

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 badges
Add a comment  | 

1 Answer 1

Reset to default 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(),
    ];
}
发布评论

评论列表(0)

  1. 暂无评论