Example #1
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)
 {
     // New objects can't be deleted, neither can frozen
     if ($this->is_new() or $this->frozen()) {
         return false;
     }
     $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::factory(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');
     return $this;
 }