简体   繁体   English

Laravel withCount包含空关系

[英]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 . 我想计算每个peoplepets数,但是我也想包括没有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. 我希望这是有道理的。

In this case, you can use ROLLUP . 在这种情况下,您可以使用ROLLUP Give it a try. 试试看。 It may help you. 它可能会帮助您。

People::withCount('pets')->groupBy(\DB::raw('id WITH ROLLUP'))->get();

to know more, please check this 要了解更多,请检查

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM