I'm building a small search in my Laravel 7.0
application. I'm having two models Project
and Company
which is into many to many
relationship with project_associate_company
intermediate table.
My tables are Project
******************** projects ***********************
| |
| id | name | area | cost | created_at | updated_at |
| 1 | Development Project | 1461 | 243 |2018-09-17 21:42:41|2018-09-17 21:42:41|
| 2 | Testing Project | 1500 | 200 |2018-09-18 21:42:41|2018-09-18 21:42:41|
Company Model:
******************** companies ***********************
| |
| id | name | state | type | created_at | updated_at |
| 1 | Demo company | Maharastra | Private | ..... | .... |
| 1 | Test company | Gujarat | Public | ..... | .... |
Pivot table (relation) table:
******************** project_associate_company ***************
| |
| id | project_id | company_id | role_id | specialisation_id |
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 | 2 |
| 3 | 2 | 1 | 1 | 1 |
| 4 | 2 | 2 | 1 | 1 |
| 5 | 1 | 2 | 4 | 2 |
|____________________________________________________________|
Now in my controller I'm having:
$companies = Company::join('project_associate_company', function ($join) {
$join->on('companies.id', '=', 'project_associate_company.company_id')
->whereNull('project_associate_company.deleted_at');
})
->join('projects', function ($join) {
$join->on('project_associate_company.project_id', '=', 'projects.id')
->whereNull('projects.deleted_at');
})
->select('companies.*',
DB::raw('count(projects.id) as projects_count'),
DB::raw('count(DISTINCT projects.id) as unique_projects_count'),
DB::raw('SUM( projects.cost) as projects_cost'),
DB::raw('SUM( projects.area) as projects_area')
)
->groupBy('companies.id')
->orderBy('projects_area', 'desc')
->paginate();
Expected results:
| id | name | projects_count | unique_projects_count | projects_area | projects_cost |
| 1 | Demo company | 3 | 2 | 2961 | 443 |
| 1 | Test company | 2 | 2 | 2961 | 443 |
But results generating:
| id | name | projects_count | unique_projects_count | projects_area | projects_cost |
| 1 | Demo company | 3 | 2 | 4422 | 686 |
| 1 | Test company | 2 | 2 | 2961 | 443 |
So whenever I'm joining projects I'm getting duplicate projects which are added multiple during CRUD operation as per role and specialisation. I need to have DISTINCT
projects where I can sum its area and cost, so that I can sort with them. Currently I'm having different projects_count
and unique_projects_count
I tried doing groupBy('companies.id')->groupBy('projects.id')
but the results are coming wrong. How can I achieve this?