Example #1
0
 /**
  * Deletes this model instance from the database.
  *
  * @return bool
  */
 protected function delete_self()
 {
     // Create the query and limit to primary key(s)
     $query = Query::forge(get_called_class(), static::connection(true))->limit(1);
     $primary_key = static::primary_key();
     foreach ($primary_key as $pk) {
         $query->where($pk, '=', $this->{$pk});
     }
     // Return success of update operation
     return $query->delete();
 }
Example #2
0
 /**
  * Delete current object
  *
  * @param   mixed  $cascade
  *     null = use default config,
  *     bool = force/prevent cascade,
  *     array cascades only the relations that are in the array
  * @return  Model  this instance as a new object without primary key(s)
  */
 public function delete($cascade = null, $use_transaction = false)
 {
     // New objects can't be deleted, neither can frozen
     if ($this->is_new() or $this->frozen()) {
         return false;
     }
     if ($use_transaction) {
         $db = \Database_Connection::instance(static::connection());
         $db->start_transaction();
     }
     try {
         $this->observe('before_delete');
         $this->freeze();
         foreach ($this->relations() as $rel_name => $rel) {
             $rel->delete($this, $this->{$rel_name}, false, is_array($cascade) ? in_array($rel_name, $cascade) : $cascade);
         }
         $this->unfreeze();
         // Create the query and limit to primary key(s)
         $query = Query::forge(get_called_class(), static::connection())->limit(1);
         $primary_key = static::primary_key();
         foreach ($primary_key as $pk) {
             $query->where($pk, '=', $this->{$pk});
         }
         // Return success of update operation
         if (!$query->delete()) {
             return false;
         }
         $this->freeze();
         foreach ($this->relations() as $rel_name => $rel) {
             $rel->delete($this, $this->{$rel_name}, true, is_array($cascade) ? in_array($rel_name, $cascade) : $cascade);
         }
         $this->unfreeze();
         // Perform cleanup:
         // remove from internal object cache, remove PK's, set to non saved object, remove db original values
         if (array_key_exists(get_called_class(), static::$_cached_objects) and array_key_exists(static::implode_pk($this), static::$_cached_objects[get_called_class()])) {
             unset(static::$_cached_objects[get_called_class()][static::implode_pk($this)]);
         }
         foreach ($this->primary_key() as $pk) {
             unset($this->_data[$pk]);
         }
         $this->_is_new = true;
         $this->_original = array();
         $this->observe('after_delete');
         $use_transaction and $db->commit_transaction();
     } catch (\Exception $e) {
         $use_transaction and $db->rollback_transaction();
         throw $e;
     }
     return $this;
 }