GetColumnAsArray('id', false); $sBulkList = implode(',', $aBulksObjects); // Get all links attached to object selection $sOqlGroupBy = "SELECT $sLinkClass AS lnk WHERE lnk.$sOriginField IN ($sBulkList)"; $oDbObjectSearch = DBSearch::FromOQL($sOqlGroupBy); // Group by links attached to object selection $oFieldExp = new FieldExpression($sTargetField, 'lnk'); $sQuery = $oDbObjectSearch->MakeGroupByQuery([$sTargetField], array('grouped_by_1' => $oFieldExp), true); $aGroupResult = CMDBSource::QueryToArray($sQuery, MYSQLI_ASSOC); // Iterate throw result... foreach ($aResult as &$aItem) { // Find group by object to extract link count $aFound = null; foreach ($aGroupResult as $aItemGroup) { if ($aItem['key'] === $aItemGroup['grouped_by_1']) { $aFound = $aItemGroup; } } // If found, get information if ($aFound !== null) { $aItem['group'] = 'Objects already linked'; $aItem['occurrence'] = $aFound['_itop_count_']; $aItem['occurrence_label'] = "Link on {$aFound['_itop_count_']} Objects(s)"; $aItem['occurrence_info'] = "({$aFound['_itop_count_']})"; $aItem['full'] = ($aFound['_itop_count_'] == $oDbObjectSetBulkObjects->Count()); // Retrieve linked objects keys $sOqlLinkKeys = "SELECT $sLinkClass AS lnk WHERE lnk.$sOriginField IN ($sBulkList) AND lnk.$sTargetField = {$aItem['key']}"; $oDbSearchLinkKeys = DBSearch::FromOQL($sOqlLinkKeys); $aLinkedObjects = new DBObjectSet($oDbSearchLinkKeys); $aItem['link_keys'] = $aLinkedObjects->GetColumnAsArray('id', false); } else { $aItem['group'] = 'Others'; $aItem['occurrence'] = ''; $aItem['empty'] = true; } } // Order items usort($aResult, [self::class, "CompareItems"]); } catch (Exception $e) { ExceptionLog::LogException($e); } } return $aResult; } /** * CompareItems. * * @param $aItemA * @param $aItemB * * @return array|int */ static private function CompareItems($aItemA, $aItemB): int { if ($aItemA['occurrence'] === $aItemB['occurrence']) { return 0; } return ($aItemA['occurrence'] > $aItemB['occurrence']) ? -1 : 1; } }