获取yii中的所有表名称

时间:2014-02-24 07:23:08

标签: mysql database yii

如何获取yii中的所有表名?

mySQL中的sql查询是SHOW TABLES。 我试过了:

$sql = 'SHOW TABLES';
$tables = Yii::app()->db
         ->createCommand($sql)
         ->queryAll();
print_r($tables);

它会抛出错误:

CDbCommand failed to execute the SQL statement:
CDbCommand failed to prepare the SQL statement:
SQLSTATE[HY000]: General error: 1 near "SHOW": syntax error.
The SQL statement executed was: SHOW TABLES 

3 个答案:

答案 0 :(得分:6)

试试这个:

$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tables = $dbSchema->getTables();//returns array of tbl schema's
foreach($tables as $tbl)
{
    echo $tbl->rawName, ':<br/>', implode(', ', $tbl->columnNames), '<br/>';
}

<强>参见: How to get all table and column names from database in Yii Framework

答案 1 :(得分:3)

如果你想使用yii,那么Mani的回答是正确的。如果要使用create命令获取表名,则可以使用

$sql='SELECT * FROM INFORMATION_SCHEMA.TABLES'
$tables = Yii::app()->db
         ->createCommand($sql)
         ->queryAll();

答案 2 :(得分:0)

简单就是这么简单:

var_dump(Yii::app()->db->schema->getTableNames();

http://www.yiiframework.com/doc/api/1.1/CDbSchema - 这里寻找详细信息