Laravel 从关系中检查值

Laravel Check for Value from Relation

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

    $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",
    },
  ]
}

我真的不需要 staff 数组,我只想检查关系中是否存在女性,然后 return 类似这样的东西:

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

有没有 eloquent 方法来实现这个?

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

像下面这样更改您的代码并查看

$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,
    ];

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

$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 上的方法。