[英]Laravel withCount include null relationship
I would like withCount to include the count of non-existent relationships. 我希望withCount包括不存在的关系的数量。
For example, let's say I have a table called people
, and a table called pets
. 例如,假设我有一个名为
people
的表和一个名为pets
的表。
people
hasmany pets
, but pets
can have a null people_id
. people
拥有许多pets
,但pets
可以具有空的people_id
。 I want to get a count of the the pets
per people
, but I also want to include pets
that does not have a people_id
. 我想计算每个
people
的pets
数,但是我也想包括没有people_id
pets
。
I know I can simply do People::withCount('pets')->get()
, but this does not include a count of pets
with null people_id
. 我知道我可以简单地执行
People::withCount('pets')->get()
,但这不包括具有null people_id
为null的pets
数。
The result I'm looking for would be something like: 我正在寻找的结果将是这样的:
person_name | pets_count
John | 2
Mike | 3
Joan | 0
NULL | 20
I hope this makes sense. 我希望这是有道理的。
You may do something like this: 您可以执行以下操作:
People::selectRaw('peoples.*, COUNT(pets.id) AS pets_count')
->rightJoin('pets', 'people.id', '=', 'pets.people_id')
->get()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.