Amirali
Amirali

Reputation: 29

Use sql queries in Laravel 6 to count the number of workers in each department

I'm new in laravel and sql. I have two models (Worker and Department) and each model has one to many relationships. Each model has db tables workers and departments. My questions are:

  1. Can we use sql query in laravel 6 to count number of workers in each department?
  2. where we can use this sql query inside controller or model?

I used this query inside controller but gives me error, what is wrong with it?

public function count()
{
   SELECT COUNT(id), department FROM Worker GROUP BY department; 
}

Upvotes: 0

Views: 353

Answers (2)

Rayann Nayran
Rayann Nayran

Reputation: 1135

Your Department Model:

class Department extends Model
{

    public function workers()
    {
        return $this->hasMany('App\Worker');
    }

}

So, you count how many workers are in each department like this:

$departments = App\Department::withCount('workers')->get();

See also:

Counting Related Models

Laravel best practices

Upvotes: 2

nvs
nvs

Reputation: 1

To use raw query in Laravel controller, you must combine it in query builder. This will work:

DB::raw("SELECT COUNT(id), department FROM Worker GROUP BY department");

Upvotes: 0

Related Questions