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.

Get table name from model name Yii

Step1: Create one controller named "CommonController.php" or use any existing one.
Step2: Create a static method in that controller named "getTableNameFromModel()" and add the following code in it.

<?php
public static function getTableNameFromModel($model) {
       return $model::model()->tableSchema->name;
}
?>

Step3: Call function from your model/view/controller by passing model name as a parameter.
<?php
    $model=new User;
    echo CommonController::getTableNameFromModel($model);
?>

It'll return table name of the corresponding model.
Hope it'll help you. Thanks.

Read Next: Get column names from model Yii