首页 > 解决方案 > 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,
  ),
) 

我试过了...

  1. 在 whereHas 之前或之后切换 with() 没有区别。
  2. 将 ->where() 添加到 with() 选择具有指定 id 的 StationJob,而不是检查 latestStation id 是否等于指定 id。

标签: laraveleloquent

解决方案


推荐阅读