1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?php
- namespace App\ModelFilters;
- 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 assetId($assetId){
- return $this->where('asset_id',$assetId);
- }
- public function groupId($groupId){
- //
- $group = RequirementGroup::find($groupId);
- if (!$group || !$group->children()->first()) {
- // 如果没有子级,只返回该分组的需求
- return $this->where('requirement_group_id', $groupId);
- }
- $allRelatedGroupIds = $this->getAllRelatedGroupIds($groupId);
- //把父级id去重
- $unIds=array_unique($allRelatedGroupIds);
- return $this->whereIn('requirement_group_id',$unIds);
- }
- private function getAllRelatedGroupIds($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->getAllRelatedGroupIds($childId));
- }
- // 添加父级ID(如果需要的话)
- if ($group->parent_id) {
- $childIds[] = $group->parent_id;
- }
- return $childIds;
- }
- }
|