atk4\data\Model::delete PHP Method

delete() public method

Delete record with a specified id. If no ID is specified then current record is deleted.
public delete ( mixed $id = null )
$id mixed
    public function delete($id = null)
    {
        if ($id == $this->id) {
            $id = null;
        }
        return $this->atomic(function () use($id) {
            if ($id) {
                $c = clone $this;
                $c->load($id)->delete();
                return $this;
            } elseif ($this->loaded()) {
                if ($this->hook('beforeDelete', [$this->id]) === false) {
                    return $this;
                }
                $this->persistence->delete($this, $this->id);
                $this->hook('afterDelete', [$this->id]);
                $this->unload();
                return $this;
            } else {
                throw new Exception(['No active record is set, unable to delete.']);
            }
        });
    }

Usage Example

Example #1
0
 public function testAtomicOperations()
 {
     $db = new Persistence_SQL($this->db->connection);
     $a = ['item' => [['name' => 'John'], ['name' => 'Sue'], ['name' => 'Smith']]];
     $this->setDB($a);
     $m = new Model($db, 'item');
     $m->addField('name');
     $m->load(2);
     $m->addHook('afterSave', function ($m) {
         throw new \Exception('Awful thing happened');
     });
     $m['name'] = 'XXX';
     try {
         $m->save();
     } catch (\Exception $e) {
     }
     $this->assertEquals('Sue', $this->getDB()['item'][2]['name']);
     $m->addHook('afterDelete', function ($m) {
         throw new \Exception('Awful thing happened');
     });
     try {
         $m->delete();
     } catch (\Exception $e) {
     }
     $this->assertEquals('Sue', $this->getDB()['item'][2]['name']);
 }
All Usage Examples Of atk4\data\Model::delete