laravel - Laravel 检查关系中的值
问题描述
我有一个看起来像这样的查询,我在其中获取特定位置的各种企业的数据,并且我需要能够判断每个企业都有(或没有)女性员工。
$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;
}
有没有一种雄辩的方法来实现这一目标?
注意:在我的原始代码中,我有更多要查询的关系,但我不得不将这篇文章限制在我的问题范围内。
解决方案
如下更改您的代码并查看
$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,
];
推荐阅读
- php - 如何在多列中搜索?
- apache-flink - 在 flink cluster 1.7.2 版本中注册事件时出现问题
- java - 如何在 Spring Boot 应用程序中调用自定义 oracle 函数?
- java - 如何将 textview 文本设置为用户每次点击按钮时输入的名称?
- javascript - if else if 带有许多 or 表达式的函数不会循环遍历所有 or 可能性
- python - Numpy有效的方法来获取矩阵中的adiacent索引或值
- spring - 春季安全应用程序中的会话被覆盖
- html - CSS Flexbox - 使用溢出滚动不可见滚动:y
- android-studio - 在 Android Studio 中导入 SVG 文件时,渐变没有停止信息错误
- python - 使用实时 Python 数据更新 Excel 电子表格