Laravel 具有计数的多个连接(不是 Eloquent)

Laravel Multiple Joins with Counts (Not Eloquent)

我要将此 Eloquent 查询转换为 Laravel 中的数据库查询。

$users = User::withCount("addresses", "cars")->get();

上面的是 Eloquent 并且运行良好。 但我想用数据库查询来做到这一点。

我尝试按照以下方式操作,但无法获得预期结果。

$users = \DB::table("users")->join("addresses", "users.id", "=", "addresses.user_id")
->join("cars", "users.id", "=", "cars.user_id") 
->selectRaw("users.id, users.name, count(addresses.id) as addresses_count, count(cars.id) as cars_count")
->groupBy("users.id", "users.name")
->get();

addresses_countcars_count的结果值相同,是2的乘积

如有任何帮助,我们将不胜感激。

您只需要在 count 中添加 distinct,例如:

$users = \DB::table("users")->join("addresses", "users.id", "=", "addresses.user_id")
->join("cars", "users.id", "=", "cars.user_id") 
->selectRaw("users.id, users.name, count(distinct addresses.id) as addresses_count, count(distinct cars.id) as cars_count")
->groupBy("users.id", "users.name")
->get();