/**
* Method to delete a row from the database table by primary key value.
*
* @param mixed $pk An optional primary key value to delete. If not set the instance property value is used.
*
* @return boolean True on success.
*
* @since 1.7.0
* @throws \UnexpectedValueException
*/
public function delete($pk = null)
{
if (\is_null($pk)) {
$pk = array();
foreach ($this->_tbl_keys as $key) {
$pk[$key] = $this->{$key};
}
} elseif (!\is_array($pk)) {
$pk = array($this->_tbl_key => $pk);
}
foreach ($this->_tbl_keys as $key) {
$pk[$key] = \is_null($pk[$key]) ? $this->{$key} : $pk[$key];
if ($pk[$key] === null) {
throw new \UnexpectedValueException('Null primary key not allowed.');
}
$this->{$key} = $pk[$key];
}
// Pre-processing by observers
$event = AbstractEvent::create('onTableBeforeDelete', ['subject' => $this, 'pk' => $pk]);
$this->getDispatcher()->dispatch('onTableBeforeDelete', $event);
// If tracking assets, remove the asset first.
if ($this->_trackAssets) {
// Get the asset name
$name = $this->_getAssetName();
/** @var Asset $asset */
$asset = self::getInstance('Asset');
if ($asset->loadByName($name)) {
if (!$asset->delete()) {
$this->setError($asset->getError());
return false;
}
}
}
// Delete the row by primary key.
$query = $this->_db->getQuery(true)->delete($this->_tbl);
$this->appendPrimaryKeys($query, $pk);
$this->_db->setQuery($query);
// Check for a database error.
$this->_db->execute();
// Post-processing by observers
$event = AbstractEvent::create('onTableAfterDelete', ['subject' => $this, 'pk' => $pk]);
$this->getDispatcher()->dispatch('onTableAfterDelete', $event);
return true;
}