You are grouping on the project_id so it will give you per project. Remove the blocks.project_id from the group by and the select and you should be good.
Getting my query to get the total amount
I have a couple of projects and each project has a block and an activity. What I'm trying to do is list all the blocks out but also get the total price of those blocks and the total planned value of those blocks and the way I've done this is that the planned values and the pricing is in 2 different tables
The problem is, is that I'm getting the totals for individual projects, but I'm trying to add them up regardless of the project_id, that piece in the query is just to make sure that I'm getting the correct blocks for that project
Here is what my tables look like
projects table
id | name
1 | project 1
2 | project 2
3 | project 3
4 | project 4
5 | project 5
blocks table
id | project_id | block_code | price
1 | 1 | PR1 | 123
2 | 1 | PR4 | 123
activities table
id | project_id | block_code | planned
1 | 1 | PR1 | 2
2 | 1 | PR4 | 3
3 | 1 | PR7 | 1
4 | 1 | PR4 | 3
Here is my query
public function getBlocks(User $user)
{
// one to many
$projects = $user->projects;
$arr = [];
foreach($projects as $project)
{
$arr[] = $project->id;
}
$query = DB::connection('testing')
->table('blocks')
->leftJoin('activities', function($join){
$join->on('blocks.project_id', '=', 'activities.project_id');
$join->on('blocks.block_code', '=', 'activities.block_code');
})
->leftJoin('projects', 'blocks.project_id', '=', 'projects.id')
->select(
'blocks.project_id',
'blocks.block_code',
DB::raw('sum(activities.planned) AS total_planned'),
DB::raw('blocks.price * sum(activities.planned) AS total_price'),
)
->whereIn('blocks.project_id', $arr)
->groupBy(
'blocks.project_id',
'blocks.block_code',
'blocks.price',
)
->get();
}
Please or to participate in this conversation.