Thursday 16 January 2014

Get column names from model Yii

In previous post we learned how to get table name from model in Yii. In this post we'll learn how to fetch all column names from model name by using our previous method.
Add the following method in your "CommonController.php" or any other which you are using.

<?php
public static function getColumnNames($table) {        
        return $table::model()->getTableSchema()->getColumnNames();
}
?>

Now call that method from your model/view/controller in this way:

<?php
$model=new User;
$table=CommonController::getTableNameFromModel($model);
$colArr=CommonController::getColumnNames($table);

// -- Output --
echo "<pre>";
print_r($colArr);
?>

It'll return you an array containing all the column names of given table.
Thanks. Have a great day.

No comments:

Post a Comment