Home > Software engineering >  Yii2 How to get all values from column (DB)
Yii2 How to get all values from column (DB)

Time:06-17

I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:

$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);

Can anyone help me?

CodePudding user response:

You can use query builder to do that:

$categories = (new \yii\db\Query())
    ->select(['category_name'])
    ->from('iab_categories')
    ->column();

The select() method sets what columns should be included in result. The from() method sets what table should be queried. And the column() method executes the query and return first column from result set as array.

EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x. So there is query builder version for Yii 1.x:

$categories = Yii::app()->db->createCommand()
    ->select('category_name')
    ->from('iab_categories')
    ->queryColumn();
  • Related