Reputation:
Consider this query and its result:
Yii::app()->db->createCommand(
"SELECT name FROM users WHERE city='Paris'"
)->queryColumn();
Result:
Array
(
[0] => John Kerry
[1] => Marry White
[2] => Mike Jain
)
Any suggestions on how to build this query with ActiveRecord
?
It is necessary to receive the array.
Upvotes: 3
Views: 12185
Reputation: 2928
Use Chtml to this is a Ugly Hack! In short, you can do this:
public function queryAll($condition = '', $params = array())
{
$criteria = $this->getCommandBuilder()->createCriteria($condition, $params);
$this->applyScopes($criteria);
$command = $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria);
$results = $command->queryAll();
return $results;
}
Follow my answer to a identical problem in other question, in this link.
Upvotes: 0
Reputation: 3559
Actually I have dealt with the same problem, I would like to use the ActiveRecord instead of CDBCommand. I have answered on the similar question before
$words = Word::model()->findAll();
$data=array_map(create_function('$m','return $m->getAttributes();'),$words);
var_dump($data);
Upvotes: 1
Reputation: 2134
Duplicate: Yii - How to get a values array from an Active Record
use CHtml::listData
(see http://www.yiiframework.com/wiki/48/by-example-chtml/#hh3 )
$users = User::model()->findAll();
$usersArr = CHtml::listData( $users, 'id' , 'city');
print_r( $usersArr );
It will give you array id => city
Array {
2 => 'Paris',
102 => 'Riga',
// ...
}
Upvotes: 7
Reputation: 1467
As already mentioned, you can use findAllByAttributes(array $attributes, mixed $condition='', array $params=array ( )) and also tell this method to fetch only the 'name' column for the records it matches. To do this, you'll need to pass as $condition an instance of CDbCriteria and specify on this instance the 'select' columns.
Upvotes: 0
Reputation: 4150
An active record, by it's name, will return a whole record for each row in your database, so the best way to obtain just one field from each row would be using the querybuilder with something like what you've got above.
If you really wanted to use AR and just want the name in an array then something like this might work:
$names = array();
$users = users::model()->findAllByAttributes(array('city'=>'Paris'));
foreach(array_keys($users) as $key)
{
$names[] = $users[$key]->name;
}
Although that's a lot of overhead to pull just the name if you're not using any other details from the AR search.
Upvotes: 1