Yii框架中如何从数据库中获取所有表名和列名 [英] How to get all table and column names from database in Yii Framework

查看:74
本文介绍了Yii框架中如何从数据库中获取所有表名和列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个模块,我想在其中执行动态相关下拉表和列名功能.

I am working on a module where I want to do dynamic dependent dropdown table and column name functionality.

例如.获取所有表名并将其显示在下拉字段中,在选择特定表后,我想在下拉字段中再次显示其所有列名.

Ex. Fetch all table names and display it in dropdown fields and after selection of particular table I want to display its all column name again in dropdown field.

问题是:

1) 如何从数据库中获取所有表名?

1) How to fetch all table name from db?

2) 以及如何从表中获取所有列名?

2) and how to fetch all column name from table?

我尝试了一些文章和论坛,例如 http://www.yiiframework.com/forum/index.php/topic/5920-how-can-i-get-the-actual-full-table-name/但它不起作用.

I tried few articles and forums like http://www.yiiframework.com/forum/index.php/topic/5920-how-can-i-get-the-actual-full-table-name/ but its not working.

任何帮助将不胜感激.

谢谢

推荐答案

很简单,使用 CDbTableSchema 类的一个实例:

It's quite simple, using an instance of the CDbTableSchema class:

echo 'Name: ', $tbl->name, ' (raw: ', $tbl->rawName, ')';
echo 'Fields: ', implode(', ', $tbl->columnNames);

等等.为此有很多方法和属性
要获取所有表,只需使用 CDbSchema此处的文档.

And so on. There's a lot of methods and properties for this
To get all tables, just use the CDbSchema class docs here.

CDbSchema 类具有公共 tableNames 属性(所有 tbl 名称的数组)和 tables 属性,包含所有元数据.数据.就是这样,真的.

the CDbSchema class has both the public tableNames property (an array of all tbl namnes) and a tables property, containing all meta-data. That's all, really.

要获得所有这些实例,以下代码就足够了:

To get to all these instances, the following code should suffice:

$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/>';
}

要创建下拉列表,您只需使用标准CHtml 对象:

To create a dropdown list, you simply use the standard CHtml object:

$options = array();
foreach($tables as $tbl)
{//for example
    $options[$tbl->rawName] = $tbl->name;
}
$dropDown = CHtml::dropDownList('tables',$tables[0]->rawName, $options);

请花一些时间阅读手册,都在那里.我还没有广泛使用 Yii,好吧,说实话,我根本没有使用过它,但我只花了 5 分钟就解决了这个问题.只需查看!每个方法/类/属性都有指向相应文件中确切行的链接!
在要求他人为您解决问题之前,先努力.

Please, spend some time Reading the manual, it's all there. I haven't used Yii that extensively, well, I haven't used it at all, to be honest, yet it only took me 5 minutes to work this out. Just look at the source! Each and every method/class/property has a link to the exact line in the corresponding file!
Before asking others to figure something out for you, put in some effort.

这篇关于Yii框架中如何从数据库中获取所有表名和列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆