Can you show the generated query?
addSelect the count of multiple rows to a query
Hello there, I'm trying to retrieve all clients and the count of the location for each client using the Database query builder. One-to-many relation between the client and locations. I'm doing this:
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
DB::table('clients')
->addSelect(['client' => function (Builder $builder) {
$builder->select('clients.name as client');
}])->groupBy('client')
->addSelect(['location' => function (Builder $builder) {
$builder->from('locations')->selectRaw('count(*) as location');
}]);
this gives me the following results:
array:2 [▼
0 => {#1560 ▼
+"id": 4
+"name": "Ahrens AG & Co. KGaA"
+"created_at": "2022-08-10 06:19:00"
+"updated_at": "2022-08-10 06:19:00"
+"client": "Ahrens AG & Co. KGaA"
+"location": 3714
}
1 => {#1556 ▼
+"id": 11
+"name": "Bachmann Römer GmbH"
+"created_at": "2022-08-10 06:19:00"
+"updated_at": "2022-08-10 06:19:00"
+"client": "Bachmann Römer GmbH"
+"location": 3714
}
]
The problem is the count of the location is not correct, I'm getting the count of all the locations in the database and not the locations of the client. A help from you will be appreciated.
I know I can use something like: Client::withCount('locations')->get() but what would be something like the withCount() method in the Database query builder world
@Abdulsalam You have 2 dots in 'clients.id'
->addSelect(['location' => function (Builder $builder) {
$builder->from('locations')->selectRaw('count(*) as location')->whereColumn('clients.id', 'locations.client_id');
}]);
Please or to participate in this conversation.