Laravel一对多关联统计无计数返回?求助获取关联客户数量
问题原因及解决办法
问题出在你用了select('location_id')指定返回字段——Laravel的withCount会自动生成一个customer_count字段(命名规则是「关联方法名+_count」),但你只选择了location_id,这个计数字段没被包含进去,所以返回结果里看不到。
两种修正方式
方式1:显式包含计数字段
在select里加上自动生成的customer_count,就能同时拿到location_id和客户注册数量:
return $this->location::withCount(["customer"]) ->select('location_id', 'customer_count') ->whereLocationId($data->location_id) ->first();
方式2:移除select语句
如果不需要严格限制返回字段,直接删掉select('location_id'),first()会返回该Location的所有字段,同时带上customer_count:
return $this->location::withCount(["customer"]) ->whereLocationId($data->location_id) ->first();
补充:withCount是通过子查询统计关联模型数量,结果会挂载到「关联方法名+_count」的字段上,必须确保这个字段被包含在返回字段列表里才能显示。
内容的提问来源于stack exchange,提问作者SNoop
相关产品推荐
相关产品推荐

