Пример #1
0
 /**
  * Load all field data into $model, using $model's primary-key on which to
  * retrieve data from the database.
  *
  * Returns TRUE on a successful load, FALSE otherwise. Throws an Exception if
  * anything unexpected happens.
  *
  * @param Model $model This instance will be populated with content from the db
  * @return bool
  * @throws Exception
  */
 public function load(Model $model)
 {
     // If no fields have been set/altered, then don't bother reloading from db
     if (!$model->hasChanged()) {
         return true;
     }
     // Find and load Model from the database
     try {
         // Prepare and execute the query for loading this Model from the database
         $DB = Database::getConnectionByModel($model);
         $primaryKeys = explode(",", $model->getPrimaryKey());
         $primaryKeyValues = $model->getPrimaryKeyValue();
         $dbTableName = $model->getDbTableName();
         $sql = 'SELECT * FROM `' . $dbTableName . '` WHERE ' . implode("=? AND ", $primaryKeys) . '=?';
         $stmt = $DB->prepare($sql);
         $stmt->execute(is_array($primaryKeyValues) ? array_values($primaryKeyValues) : [$primaryKeyValues]);
         // When a single record is found, populate the Model
         $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
         if (count($records) == 1) {
             // Populate
             $model->populateFromArray($records[0]);
             $model->isInDatabase(true);
             $model->hasChanged(false);
             // Result
             return true;
         } else {
             if (count($records) == 0) {
                 return false;
             } else {
                 $fnDump = implode(", ", array_keys($model->getDbData()));
                 $fvDump = "'" . implode("', '", array_values($model->getDbData())) . "'";
                 SystemLog::add("Found multiple Models on primary key (type:{$model->modelName}, table:{$model->getDbTableName()}, data:[{$fnDump}] => [{$fvDump}]", SystemLog::WARNING);
                 return false;
             }
         }
     } catch (Exception $e) {
         SystemLog::add($e->getMessage(), SystemLog::WARNING);
         throw new Exception($e->getMessage());
         return false;
     }
 }