laravel - Laravel whereHas 没有按预期过滤
问题描述
涉及的 2 个模型是 JobRequest 和 StationJob。真的,他们的关系是一对多的。我为此 $jobRequest->stationJobs() 建立了关系。
除此之外,我还需要一个基于相同模型的 hasOne 关系 latestStation。我需要这种关系来根据 JobRequest 是否具有等于指定站点的 latestStation 来过滤我的 JobRequests 集合。
我希望得到一个空的 JobRequests 列表,因为我知道 latestStation 等于 id 3,并且我正在过滤 id 2。相反,我得到了 jobRequest,尽管我正在过滤 2,但 latestStation id 为 3。
关系
public function latestStationTest()
{
return $this->hasOne(StationJob::class)->whereNotNull('finished')->latest();
}
控制器
$stationId = $request->station_id;
$jobRequests = JobRequest::with(['latestStationTest'])->whereHas('latestStationTest', function($query) use ($stationId) {
$query->where('station_id', $stationId);
})->get();
查询结果
[2020-10-17 07:39:07] local.INFO: array (
0 =>
array (
'query' => 'select * from `job_requests` where exists (select * from `station_jobs` where `job_requests`.`id` = `station_jobs`.`job_request_id` and `station_id` = ? and `finished` is not null)',
'bindings' =>
array (
0 => 2,
),
'time' => 1.0,
),
1 =>
array (
'query' => 'select * from `station_jobs` where `finished` is not null and `station_jobs`.`job_request_id` in (1) order by `created_at` desc',
'bindings' =>
array (
),
'time' => 0.5,
),
)
我试过了...
- 在 whereHas 之前或之后切换 with() 没有区别。
- 将 ->where() 添加到 with() 选择具有指定 id 的 StationJob,而不是检查 latestStation id 是否等于指定 id。
解决方案
推荐阅读
- python - 根据其组属性过滤 DataFrame
- spring-boot - Spring数据中的实体继承
- ddev - 如何在 ddev 的容器中设置环境变量?
- javascript - 创建数字数组的函数式方法
- c# - 选择 TOP 5 通过代码调用时只返回一行,其中相同的脚本在 SQL Server 中返回 5 行
- reactjs - 如何从谷歌分析中检索 UTM 源?- 反应
- ios - Swift 4 中的委托模式不起作用!谁能解释 Swift 4 中正确的委托模式?
- qt - QSlider 在 UI 上明显滞后
- node.js - 对话框委托指令状态不变
- c++ - 定义 constexpr 静态数据成员