如何使用CakePHP截断表?

| 我想用CakePHP模型截断我的数据库表,我使用了
$this->Model->deleteAll
代码,并且工作正常。 现在,我想要的是,下次每次插入新记录时,它都应仅以1开始
ID
,而
deleteAll
函数不起作用,因此是否有任何默认的CakePHP语法来使表Truncate正常运行? 让我知道 !     
已邀请:
注意:此答案仅在CakePHP 1.3之前有效。我没有在Never版本上使用过它,所以我不知道它是否有效。
deleteAll
仅删除数据,不会截断表。 您需要调用
query()
方法。
$this->Model->query(\'TRUNCATE TABLE table_name_in_mysql;\')
http://book.cakephp.org/view/1027/query     
@JohnP \'s没有考虑在database.php中配置的表前缀。这是一种稍微更可靠的方法。 附加到每个模型的DboSource对象已经具有完全满足我们需要的fullTableName()方法。 首先,创建
Model/AppModel.php
(如果尚不存在),然后向其中添加此方法:
/**
 * fullTableName
 *
 * Provides access to the Model\'s DataSource\'s ::fullTableName() method.
 * Returns the fully quoted and prefixed table name for the current Model.
 *
 * @access public
 * @param boolean $quote Whether you want the table name quoted.
 * @param boolean $schema Whether you want the schema name included.
 * @return string  Full quoted table name.
 */
public function fullTableName($quote = true, $schema = true) {
    $datasource = $this->GetDataSource();
    return $datasource->fullTableName($this, $quote, $schema);
}
这样,您就可以在Cake应用程序中获取任何Model的完整表名,包括前缀:
$this->Model->fullTableName();
我们可以做得更好。接下来,也将此方法添加到AppModel中:
/**
 * truncate
 *
 * Truncates ALL RECORDS from the Model it is called from! VERY DANGEROUS!
 * Depends on the ::fullTableName() method to concatenate the configured
 * table prefix and table name together and quote the whole bit properly.
 *
 * @access  public
 * @return  mixed
 */
public function truncate() {
    $fullName = $this->fullTableName();
    $q = \'TRUNCATE TABLE %s\';
    return $this->query(sprintf($q, $fullName));
}
现在,您可以(轻松地,请小心!)截断应用程序中的任何Model,如下所示:
$this->Model->truncate();
而且,如果您需要调整SQL查询以匹配其他数据源,则可以在应用程序的中心位置进行调整。如果特定模型使用具有不同语法的其他DataSource,则还可以轻松覆盖easily11ѭ方法。     
CakePHP的数据库驱动程序不可知解决方案3: 创建一个
AppTable.php
,并使您所有的表都扩展此表。 添加此功能:
public function truncate()
{
    $truncateCommands = $this->schema()->truncateSql($this->connection());
    foreach ($truncateCommands as $truncateCommand) {
        $this->connection()->query($truncateCommand);
    }
}
然后只需调用
$table->truncate();
,它就会截断该表,而不管您使用哪个数据库驱动程序。     

要回复问题请先登录注册