TRUNCATE table + Zend Framework
I'm doing it:
$data = array('coords' => $district->getCoords(),
'id' => $district->getId(),
'fid' => $district->getFid(),
'wijziging'=> $district->getWijziging(),
'nieuwnr' => $district->getNieuwnr(),
'naam' => $district->getNaam(),
'wijk' => $district->getWijk(),
'wijknr' => $district->getWijknr(),
'objectid' => $district->getObjectid(),
'area' => $district->getArea(),
'len' => $district->getLen(),
);
$this->_dbTable->insert($data);
_dbTable → links to the "Districts" table.
Now I want to clear the table first before inserting data.
How can i do this?
+3
nielsv
source
to share
5 answers
Try to get an adapter if you really need to trim the table
$this->_dbTable->getAdapter()->query('TRUNCATE TABLE '.$this->_dbTable->info(Zend_Db_Table::NAME));
+11
shukshin.ivan
source
to share
Try:
$this->_dbTable->delete("1=1");
Take care of your problem. 1 = 1 will match all records, deleting them. As far as I know, there is no truncation method in Zend_Db or PDO.
@Rikesh is right, take a moment to browse the faq , after which you will get much better help.
+4
Iznogood
source
to share
Extend Zend_Db_Table_Abstract and add:
/**
* Remove all contents of the table
* @return this
*/
public function truncate()
{
$this->getAdapter()->query('TRUNCATE TABLE `' . $this->_name . '`');
return $this;
}
+3
xanld
source
to share
If you are using Zend Framework 2 with tableGateway, the process is very similar.
$query = $this->tableGateway->getAdapter()->query('TRUNCATE TABLE '.$this->tableGateway->getTable());
$query->execute();
+1
Mattkun
source
to share
<?php
namespace MyNamespace\Db\Sql;
use Zend\Db\Adapter\ParameterContainer;
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\Adapter\Driver\DriverInterface;
use Zend\Db\Sql\AbstractPreparableSql;
use Zend\Db\Sql\TableIdentifier;
class Truncate extends AbstractPreparableSql
{
/**@#+
* @const string
*/
const SPECIFICATION_TRUNCATE = 'truncate';
/**@#-*/
/**
* @var string[]
*/
protected $specifications = [
self::SPECIFICATION_TRUNCATE => /* @lang SQL */ 'TRUNCATE TABLE %1$s',
];
/**
* @var string|TableIdentifier
*/
protected $table = '';
/**
* @param null|string|TableIdentifier $table
*/
public function __construct($table = null)
{
if ($table) {
$this->table($table);
}
}
/**
* @param string|TableIdentifier $table
* @return self
*/
public function table($table)
{
$this->table = $table;
return $this;
}
/**
* @param PlatformInterface $platform
* @param DriverInterface|null $driver
* @param ParameterContainer|null $parameterContainer
* @return string
*/
protected function processTruncate(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
return sprintf(
$this->specifications[static::SPECIFICATION_TRUNCATE],
$this->resolveTable($this->table, $platform, $driver, $parameterContainer)
);
}
}
$truncate = new Truncate('table');
return $this->getSql()->prepareStatementForSqlObject($truncate)->execute();
0
B. Asselin
source
to share