0

我有一个看起来像这样的查询,我在其中获取特定位置的各种企业的数据,并且我需要能够判断每个企业都有(或没有)女性员工。

    $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;
}

有没有一种雄辩的方法来实现这一目标?

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

4

2 回答 2

0

如下更改您的代码并查看

$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,
    ];
于 2020-06-27T03:31:58.350 回答
0

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

$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 上的一种方法以提高可读性。

于 2020-06-27T03:41:00.733 回答