如何使用CakePHP截断表格?

9
我想使用CakePHP Model截断我的数据库表,我已经使用了$this->Model->deleteAll代码来实现这一目的,它也运行良好。
现在,我希望下次插入新记录时,它应该从1开始作为ID,但这不适用于deleteAll函数,那么是否有默认的CakePHP语法可以使表格截断
请告诉我!

1
可以通过以下代码实现:$this->Model->query('TRUNCATE TABLE table_name'); - Aditya P Bhatt
3个回答

16

注意:此答案仅适用于CakePHP 1.3。我没有在较新版本上使用过,所以不知道它是否有效。

deleteAll只删除数据,而不是截断表。

你需要调用query()方法。

$this->Model->query('TRUNCATE TABLE table_name_in_mysql;')

http://book.cakephp.org/view/1027/query


只有一个警告——它是针对MySQL特定的,并不是所有DBMS都支持truncate。它在SQL:2008标准中正式引入。 - gaRex
2
应该是 $this->Model->query('TRUNCATE table tablename;') 吧? - trante
@trante,我按照你的方法尝试了,但是查询无法执行。我该怎么办? - Raphaël Colantonio
@DoNhuVy 这个答案已经有好几年了,而且我已经很久没有使用过 Cake 了。很抱歉,需要有人来介入新的 CakePHP。 - JohnP
它在CakePHP 2.X上与Mysql一起工作。"tablename"应该是mysql表的名称,而不是别名或模型名称。 - Jorge Ramirez

3

@JohnP的做法没有考虑到在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应用程序中任何模型的完整表名,包括前缀:

$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));
}

现在你可以轻松地截断应用程序中的任何模型,像这样:$this->Model->truncate();。如果您需要调整SQL查询以匹配不同的数据源,可以在应用程序的中心位置进行操作。如果某些模型使用不同的数据源和不同的语法,则还可以轻松地覆盖truncate()方法。请注意,操作要小心!

0
一个适用于CakePHP 3的数据库驱动程序无关解决方案:
创建一个名为AppTable.php的文件,并让所有的表都继承它。
在该文件中添加以下函数:
public function truncate()
{
    $truncateCommands = $this->schema()->truncateSql($this->connection());
    foreach ($truncateCommands as $truncateCommand) {
        $this->connection()->query($truncateCommand);
    }
}

然后只需调用$table->truncate();,它应该会截断表格,无论您使用哪个数据库驱动程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接