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.
The issues are:
1) How to fetch all table name from db?
2) and how to fetch all column name from table?
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.
Any help would be appreciated.
Thanks
It's quite simple, using an instance of the CDbTableSchema
class:
echo 'Name: ', $tbl->name, ' (raw: ', $tbl->rawName, ')';
echo 'Fields: ', implode(', ', $tbl->columnNames);
And so on. There's a lot of methods and properties for this
To get all tables, just use the CDbSchema
class docs here .
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/>';
}
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);
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 .
fetch all column name from table:
TableName::model()->getTableSchema()->getColumnNames();
It'll return an array containing all the column names of TableName.
fetch all column name and labels:
$fields=Tablename::attributeLabels();
foreach($fields as $key=>$value){
echo "column name : ".$key." and label ".$value."<br/>";
}
it will display all fieldname and label value from modal.....
To get both Tables and Columns refer This Answer , I have pasted the sample code here below, please visit that answer for more explanations.
$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/>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.