@JohnP's 不考虑在database.php 中配置的表前缀。这是一种更强大的方法。
附加到每个模型的 DboSource 对象已经有一个 fullTableName() 方法,它可以满足我们的需要。
首先,create 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 应用中为 any 模型获取完整的表名,包括前缀:
$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 查询以匹配不同的数据源,您可以在应用的中心位置执行此操作。如果特定模型使用具有不同语法的不同 DataSource,您还可以轻松覆盖 truncate() 方法。