Laravel 预加载删除子项上的空值

Laravel Eager Loading removing empty values on children

我有这种急切的关系:

$companies = Company::with('employees.records')->get();

如果员工没有记录,我不想将其包含在结果中。这是我的最终查询:

$companies = Company::whereIn('name', ['A', 'B'])->with([
    'employees' => function ($employee) use ($startDate, $endDate) {
        return $employee->with([
            'records' => function ($record) use ($startDate, $endDate) {
                return $record->whereBetween('date', [$startDate, $endDate]);
            }
        ]);
    }
])->get();

如果有员工的记录或 none 我想要的输出:

{
  "data": [
    {
      "id": 1,
      "name": A,
      "records": [] 
    },
    {
      "id": 2,
      "name": B,
      "records": [
        {
          "id": 1,
          "name": "Check in at the office.",
          "date": "2018/09/08"
        }
      ] 
    }
  ]
}

现在这就是我得到的:

{
  "data": [
    {
      "id": 1,
      "name": A,
      "employees": [
        {
          "id": 1,
          "company_id": 1,
          "records": []
        }
      ] 
    },
    {
      "id": 2,
      "name": B,
      "employees": [
        {
          "id": 1,
          "company_id": 2,
          "records": [
            {
              "id": 1,
              "employee_id": 1,
              "name": "Check in at the office.",
              "date": "2018/09/08"
            }
          ]
        }
      ] 
    }
  ]
}

如果员工没有交易,我如何修改我的查询以删除记录?需要一些很棒的帮助。

您很可能可以使用 有很多通过 关系。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    /**
     * Get all of the records for the company.
     */
    public function records()
    {
        return $this->hasManyThrough(Record::class, Employee::class);
    }
}

https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

那么您的查询将如下所示

$companies = Company::with(['records' => function ($query) use ($startDate, $endDate) {
    $query->whereBetween('date', [$startDate, $endDate]);
}])->whereIn('name', ['A', 'B'])->get();