records, 'id') as $id) { if ($id) { $ids[] = (int) $id; } } if ($ids) { $idsList = implode(",", array_filter($ids)); $preExisting = array_column(CRM_Core_DAO::executeQuery( "SELECT id FROM civicrm_contact_category WHERE id IN ($idsList)" )->fetchAll(), 'id'); // Any where we were given an ID that doesn't exist are important. foreach (array_diff($ids, $preExisting) as $unknownID) { CRM_Core_DAO::executeQuery("INSERT INTO civicrm_contact_category (id) VALUES ($unknownID)"); } } // Now let it proceed as normal. parent::_run($result); } }