/** * set patient allergies to be the allergies identified by the array of ids. Other allergies will be removed * @param $allergy_ids * @throws Exception */ public function assignAllergies($allergy_ids) { $insert_allergy_ids = $allergy_ids; $remove_allergy_ids = array(); // Check existing allergies foreach ($this->allergies as $allergy) { if (($key = array_search($allergy->id, $insert_allergy_ids)) !== false) { // Allergy unchanged, don't remove or insert unset($insert_allergy_ids[$key]); } else { // Allergy removed $remove_allergy_ids[] = $allergy->id; } } // Insert new allergies foreach ($insert_allergy_ids as $allergy_id) { $paa = new PatientAllergyAssignment(); $paa->patient_id = $this->id; $paa->allergy_id = $allergy_id; if (!$paa->save()) { throw new Exception("Unable to save patient_allergy_assignment: " . print_r($paa->getErrors(), true)); } } $criteria = new CDbCriteria(); $criteria->addCondition('patient_id = :patient_id'); $criteria->params[':patient_id'] = $this->id; $criteria->addInCondition('allergy_id', $remove_allergy_ids); PatientAllergyAssignment::model()->deleteAll($criteria); }
/** * adds an allergy to the patient * * @param Allergy $allergy * @param string $other * @throws Exception */ public function addAllergy(Allergy $allergy, $other = null, $comments = null, $startTransaction = true) { if ($allergy->name == 'Other') { if (!$other) { throw new Exception("No 'other' allergy specified"); } } else { if (PatientAllergyAssignment::model()->exists('patient_id=? and allergy_id=?', array($this->id, $allergy->id))) { throw new Exception("Patient is already assigned allergy '{$allergy->name}'"); } } if ($startTransaction) { $transaction = Yii::app()->db->beginTransaction(); } try { $paa = new PatientAllergyAssignment(); $paa->patient_id = $this->id; $paa->allergy_id = $allergy->id; $paa->comments = $comments; $paa->other = $other; if (!$paa->save()) { throw new Exception('Unable to add patient allergy assignment: ' . print_r($paa->getErrors(), true)); } $this->audit('patient', 'add-allergy'); if ($this->no_allergies_date) { $this->no_allergies_date = null; if (!$this->save()) { throw new Exception('Could not remove no allergy flag: ' . print_r($this->getErrors(), true)); } } $this->audit('patient', 'remove-noallergydate'); if ($startTransaction) { $transaction->commit(); } } catch (Exception $e) { if ($startTransaction) { $transaction->rollback(); } throw $e; } }