Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

913
Visualizações
Relationship between two tables - Laravel, Inertia, Vuejs

I'm new to the subject, I have two tables related to each other, one for departments and one for users, I want to know how many users there are in each department

DepartmentController.php

public function index()
{
    return Inertia::render('back/app/departments/index', [
        'filters'       => request()->all('visibility', 'status', 'search'),
        'departments'   => Department::orderBy('name')->get(),
        'total_members' => User::where('department_id')->count(),

        dd(User::where('department_id')->count()),
    ]);
}

Index.vue

<td class="flex items-center text-sm leading-5 text-gray-500 px-6 py-4 whitespace-no-wrap">
    <span class="font-medium">{{ department.total_members }}</span>&nbsp;{{ $trans('labels.members') }}
</td>
<td class="px-6 py-4 whitespace-no-wrap text-right text-sm leading-5 font-medium">
    <inertia-link :href="route('app:projectdepartment.index', {id: department.id})">
        {{ $trans('labels.view-activity') }}
    </inertia-link>
</td>
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

If you have the users relationship set up on your Department model, you could use the withCount() method:

Department::withCount('users')->orderBy('name')->get()

This will give you a users_count property on each department.

over 4 years ago · Santiago Trujillo Relatório

0

Assuming you have the relationships defined on each model as noted, you could also define an accessor or as was already stated get the number of related models by way of withCount or also with loadCount after retrieving an individual Department model.

Models/User.php

  public function department()
  {
    return $this->belongsTo(Department::class, 'department_id');
  }

  public function getActiveUserCountAttribute($value)
  {
    // Perform additional logic on the users relationship
    return $this->users()->where('active',1)->count();
  }

Models/Department.php

  public function users()
  {
    return $this->hasMany(User::class);
    
  }

Remember that one of the benefits of withCount is that it doesn't load the related models, avoiding an n+1 problem. If you use withCount, you wouldn't need the accessor defined on the Department model but would need the User relationship defined on Department.

Note that you could also use the loadCount method after you have already retrieved the Department model, e.g. for an individual show page as opposed to a collection.

// From your show method in your controller

$department = Department::where('name',$request['name'])->first();
$department->loadCount('users');

To eager load the 'active_user_count' attribute on each Department model, you would use the $with property. With this defined, you would not need to use the withCount or similar in your controller method.

// Department.php

// A relationship that should always be loaded with every Department request.
protected $with = ['active_user_count']

Laravel docs: https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda