12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace App\ModelFilters;
- use App\Models\Asset;
- use Carbon\Carbon;
- use EloquentFilter\ModelFilter;
- class PlanFilter extends ModelFilter
- {
- /**
- * Related Models that have ModelFilters as well as the method on the ModelFilter
- * As [relationMethod => [input_key1, input_key2]].
- *
- * @var array
- */
- public $relations = [];
- public function apply($query)
- {
- return $query;
- }
- public function assetId($assetId)
- {
- $asset = Asset::find($assetId);
- if (!$asset || !$asset->children()->first()) {
- // 如果没有子级,只返回该分组的需求
- return $this->where('asset_id', $assetId);
- }
- $allRelatedIds = $this->getAllRelatedIds($assetId);
- array_push($allRelatedIds, $asset->id);
- //把父级id去重
- $unIds=array_unique($allRelatedIds);
- return $this->whereIn('asset_id',$unIds);
- }
- private function getAllRelatedIds($assetId)
- {
- $asset = Asset::find($assetId);
- //$group = RequirementGroup::find($groupId);
- if (!$asset) {
- return [];
- }
- // 获取所有子级ID
- $childIds = $asset->children()->pluck('id')->toArray();
- // 递归获取所有子级的子级ID
- foreach ($childIds as $childId) {
- $childIds = array_merge($childIds, $this->getAllRelatedIds($childId));
- }
- return $childIds;
- }
- public function expired($expired): PlanFilter
- {
- if (! in_array($expired, ['yes', 'no'])) {
- return $this;
- }
- return $this->when($expired == "yes", function ($query) {
- return $query->where('end', "<=", Carbon::now()->toDateString());
- })->when($expired == "no", function ($query) {
- return $query->where('end', ">", Carbon::now()->toDateString())->orWhereNull('end');
- });
- }
- }
|