拉拉维尔从关系中检查值



我有一个如下所示的查询,我获取特定位置的各种企业的数据,我需要能够判断每个企业都有(或没有(女性员工。

$business = Business::where('location', $location)
->with(['staff'])
->get();

return MiniResource::collection($business);

我的迷你资源如下所示:

return [
'name' => $this->name,
'location' => $this->location,
'staff' => PersonResource::collection($this->whenLoaded('staff')),
];

示例响应如下所示:

{
"id": 1,
"name": "XYZ Business"
"location": "London",
"staff": [
{
"name": "Abigail",
"gender": "f",
"image": "https://s3.amazonaws.com/xxxx/people/xxxx.png",
"role": "Project Manager",
},
{
"name": "Ben",
"gender": "m",
"image": "https://s3.amazonaws.com/xxxx/people/xxxx.png",
"role": "Chef",
},
]
}

我真的不需要工作人员数组,我只想检查关系中是否存在女性,然后返回类似于以下内容的内容:

{
"id": 1,
"name": "XYZ Business"
"country": "USA",
"has_female_employee": true;
}

有没有雄辩的方法来实现这一点?

注意:在我的原始代码中,我查询了更多关系,但我不得不将这篇文章限制在我的问题范围内。

如果您只寻找男性或女性工作人员,您可以像这样实现:

$someQuery->whereHas('staff', function ($query) {
$query->where('gender', 'f');
})

如果你想要两种性别,我不会经历在查询中实现这一点的麻烦,但建议减少 MiniResource 中的结果收集:

return [
'name' => $this->name,
'location' => $this->location,
'has_female_employee' => $this->whenLoaded('staff')->reduce(
function ($hasFemale, $employee) {
$hasFemale = $hasFemale || ($employee->gender === 'f'); 
return $hasFemale;
}, false),
];

更好的方法是将其创建为MiniResource上的一种方法以提高可读性。

像下面这样更改代码,然后查看

$business = Business::where('location', $location)
->with(['staff'])
->where('gender', 'f')
->get();
return [
'name' => $this->name,
'location' => $this->location,
'has_female_employee' => empty($this->whenLoaded('staff')) ? false : true,
];

最新更新