【问题标题】:Laravel Eager Loading removing empty values on childrenLaravel Eager Loading 删除子项的空值
【发布时间】:2021-12-03 14:28:16
【问题描述】:

我有这种急切的加载关系:

$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();

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

{
  "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"
            }
          ]
        }
      ] 
    }
  ]
}

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

【问题讨论】:

    标签: laravel eloquent eager-loading eloquent-relationship


    【解决方案1】:

    您很可能可以使用 Has Many Through 关系。

    <?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();
    

    【讨论】:

    • 谢谢!这绝对有很大帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2020-05-23
    • 2020-11-09
    • 2017-09-17
    • 2014-05-28
    相关资源
    最近更新 更多