Filtering and counting related model data

0

Company hasMany SectorCompany

SectorCompany belongsTo Company

SectorCompany hasMany Employee

Officer belongsTo SectorCompany

With this data in hand, how do I count how many officials with id_status = 1 are allocated to sectors of type="Administrative" ? I tried the way below but it did not work and I think I'm far from right.

{{ $empresa->SetorEmpresa->where('tipo', 'Administrativo')->Funcionario->where('id_status', 1)->count() }}

I'm using Laravel 5.1 and this data will be loaded into a view from the Enterprise object.

    
asked by anonymous 09.05.2016 / 19:10

1 answer

0

Well, I got it this way:

{{ $adm = 0 }}

@foreach($empresa->SetorEmpresa->where('tipo', 'Administrativo') as $setor_adm)
     {{ $adm += $setor_adm->Funcionario->where('id_status', 1)->count() }}
@endforeach

{{ $adm }}

So it traverses all the administrative sectors of the company and counts how many active employees it has in each of them

    
10.05.2016 / 22:12