RequirementFilter.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\ModelFilters;
  3. use App\Models\Requirement;
  4. use App\Models\RequirementGroup;
  5. use EloquentFilter\ModelFilter;
  6. class RequirementFilter extends ModelFilter
  7. {
  8. /**
  9. * Related Models that have ModelFilters as well as the method on the ModelFilter
  10. * As [relationMethod => [input_key1, input_key2]].
  11. *
  12. * @var array
  13. */
  14. public $relations = [];
  15. public function apply($query)
  16. {
  17. return $query;
  18. }
  19. public function assetId($assetId){
  20. return $this->where('asset_id',$assetId);
  21. }
  22. public function groupId($groupId){
  23. //
  24. $group = RequirementGroup::find($groupId);
  25. if (!$group || !$group->children()->first()) {
  26. // 如果没有子级,只返回该分组的需求
  27. return $this->where('requirement_group_id', $groupId);
  28. }
  29. $allRelatedGroupIds = $this->getAllRelatedGroupIds($groupId);
  30. //把父级id去重
  31. $unIds=array_unique($allRelatedGroupIds);
  32. return $this->whereIn('requirement_group_id',$unIds);
  33. }
  34. private function getAllRelatedGroupIds($groupId)
  35. {
  36. $group = RequirementGroup::find($groupId);
  37. if (!$group) {
  38. return [];
  39. }
  40. // 获取所有子级ID
  41. $childIds = $group->children()->pluck('id')->toArray();
  42. // 递归获取所有子级的子级ID
  43. foreach ($childIds as $childId) {
  44. $childIds = array_merge($childIds, $this->getAllRelatedGroupIds($childId));
  45. }
  46. // 添加父级ID(如果需要的话)
  47. if ($group->parent_id) {
  48. $childIds[] = $group->parent_id;
  49. }
  50. return $childIds;
  51. }
  52. }