Ejemplo n.º 1
0
 /**
  * Method to load a row from the database by primary key and bind the fields
  * to the AbstractTable instance properties.
  *
  * @param   mixed    $keys   An optional primary key value to load the row by, or an array of fields to match.  If not
  *                           set the instance property value is used.
  * @param   boolean  $reset  True to reset the default values before loading the new row.
  *
  * @return  static  Method allows chaining
  *
  * @since   2.0
  * @throws  \RuntimeException
  * @throws  \UnexpectedValueException
  * @throws  \InvalidArgumentException
  */
 public function load($keys = null, $reset = true)
 {
     if (empty($keys)) {
         $empty = true;
         $keys = array();
         // If empty, use the value of the current key
         foreach ($this->keys as $key) {
             $empty = $empty && empty($this->{$key});
             $keys[$key] = $this->{$key};
         }
         // If empty primary key there's is no need to load anything
         if ($empty) {
             return $this;
         }
     } elseif (!is_array($keys)) {
         // Load by primary key.
         $keyCount = count($this->keys);
         if ($keyCount) {
             if ($keyCount > 1) {
                 throw new \InvalidArgumentException('Table has multiple primary keys specified, only one primary key value provided.');
             }
             $keys = array($this->getKeyName() => $keys);
         } else {
             throw new \RuntimeException('No table keys defined.');
         }
     }
     // Event
     $this->triggerEvent('onBefore' . ucfirst(__FUNCTION__), array('conditions' => &$keys, 'reset' => &$reset));
     if ($reset) {
         $this->reset();
     }
     // Initialise the query.
     $query = $this->db->getQuery(true);
     $query->select('*');
     $query->from($this->db->quoteName($this->table));
     foreach ($keys as $field => $value) {
         // Check that $field is in the table.
         if (isset($this->data->{$field}) || is_null($this->data->{$field})) {
             // Add the search tuple to the query.
             $query->where($this->db->quoteName($field) . ' = ' . $this->db->quote($value));
         } else {
             throw new \UnexpectedValueException(sprintf('Missing field in database: %s   %s.', get_class($this), $field));
         }
     }
     $this->db->setQuery($query);
     $row = $this->db->loadOne();
     // Check that we have a result.
     if (empty($row)) {
         throw new NoResultException('No result.');
     }
     // Bind the object with the row and return.
     $row = $this->bind($row);
     // Event
     $this->triggerEvent('onAfter' . ucfirst(__FUNCTION__), array('result' => &$row));
     return $row;
 }