Reputation: 29
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:
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
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:
Upvotes: 2
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