update:优化用户的部门搜索,减少SQL

This commit is contained in:
JaguarJack 2020-11-04 10:06:23 +08:00
parent 97b7f73ff2
commit 7c4fa5c516
2 changed files with 20 additions and 15 deletions

View File

@ -40,25 +40,22 @@ class Department extends CatchModel
->select()->toTree();
}
/**
* 获取部门
* 获取部门IDS
*
* @time 2020年11月04日
* @param array $departmentIds
* @param $id
* @throws DbException
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @return array
* @return mixed
*/
public static function getAllChildrenIds(array $departmentIds)
public static function getChildrenDepartmentIds($id)
{
$childDepartmentIds = self::whereIn('parent_id', $departmentIds)->column('id');
$departmentIds = Department::field(['id', 'parent_id'])->select()->getAllChildrenIds([$id]);
if (!empty($childDepartmentIds)) {
$childDepartmentIds = array_merge($childDepartmentIds, self::getAllChildrenIds($childDepartmentIds));
}
$departmentIds[] = $id;
return $childDepartmentIds;
return $departmentIds;
}
}

View File

@ -20,12 +20,20 @@ trait UserSearch
return $query->where($this->aliasField('status'), $value);
}
/**
* 查询部门下的用户
*
* @time 2020年11月04日
* @param $query
* @param $value
* @param $data
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return mixed
*/
public function searchDepartmentIdAttr($query, $value, $data)
{
$departmentIds = Department::getAllChildrenIds([$value]);
$departmentIds[] = intval($value);
return $query->whereIn($this->aliasField('department_id'), $departmentIds);
return $query->whereIn($this->aliasField('department_id'), Department::getChildrenDepartmentIds($value));
}
}