Laravel Eager Loading 删除子项的空值
Posted
技术标签:
【中文标题】Laravel Eager Loading 删除子项的空值【英文标题】:Laravel Eager Loading removing empty values on children 【发布时间】: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"
]
]
]
如果员工没有交易,我如何修改查询以删除记录?需要一些很棒的帮助。
【问题讨论】:
【参考方案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();
【讨论】:
谢谢!这绝对有很大帮助!以上是关于Laravel Eager Loading 删除子项的空值的主要内容,如果未能解决你的问题,请参考以下文章
Laravel Eager Loading - 仅加载特定列
Laravel:Eloquent Eager Loading 关系的选择
Laravel Eager Loading 和动态绑定模型关系