12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- namespace App\ModelFilters;
- use App\Models\Asset;
- use App\Models\Requirement;
- use App\Models\RequirementGroup;
- use EloquentFilter\ModelFilter;
- class RequirementFilter 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 plan($plan_id){
- return $this->where('plan_id',$plan_id);
- }
- public function assetId($assetId){
- //$assetId = Asset::query()->where('id',$assetId)->pluck('id');
- return $this->where('asset_id',$assetId);
- }
- public function group($groupId){
- if($groupId==0){
- return $this->whereNull('requirement_group_id');
- }
- //
- $group = RequirementGroup::find($groupId);
- if (!$group || !$group->children()->first()) {
- // 如果没有子级,只返回该分组的需求
- return $this->where('requirement_group_id', $groupId);
- }
- $allRelatedGroupIds = $this->getAllGroupRelatedIds($groupId);
- //把父级id去重
- $unIds=array_unique($allRelatedGroupIds);
- return $this->whereIn('requirement_group_id',$unIds);
- }
- //递归获取需求分组
- private function getAllGroupRelatedIds($groupId)
- {
- $group = RequirementGroup::find($groupId);
- if (!$group) {
- return [];
- }
- // 获取所有子级ID
- $childIds = $group->children()->pluck('id')->toArray();
- // 递归获取所有子级的子级ID
- foreach ($childIds as $childId) {
- $childIds = array_merge($childIds, $this->getAllGroupRelatedIds($childId));
- }
- // 添加父级ID(如果需要的话)
- if ($group->parent_id) {
- $childIds[] = $group->parent_id;
- }
- return $childIds;
- }
- }
|