i have db table user (user_id, name)
need fetch array [user_id => name]
how fetch this array use phalcon methods?
in yii there is method indexBy
why it does not have?
|
May '16 |
6 |
774 |
0 |
Honestly i was looking for such solution also, but could not find any. Actually im needing it 2-3 times per project, so i ended up adding a method in my model (like Dylan's suggestion). Something like that you can reuse:
public function getAllForSelect()
{
$lang = $this->getDI()->getSession()->language;
$items = CategoriesI18n::find([
'columns' => ['foreign_key', 'title'],
'conditions' => 'lang = :lang:',
'bind' => [
'lang' => $lang
],
'order' => 'title ASC',
'cache' => ['lifetime' => 360000, 'key' => 'categories-all-for-select-'. $lang]
]);
$collection = [];
foreach ($items as $item) {
$collection[$item->foreign_key] = $item->title;
}
return $collection;
}
class Users extends BaseModel{}
class BaseModel extends \Phalcon\Mvc\Model {
public function indexBy($params) {
// blabla
}
}
You have the option to overwrite default model methods, also to create new ones, something simple like above..
Thats the good thing about Phalcon it is not stuffed with useless classes that you may never need.. like email sending class, pdf generator, xls reader or even Stripe payment in Larabel.. who the fuk cares about those ? :)
Honestly i was looking for such solution also, but could not find any. Actually im needing it 2-3 times per project, so i ended up adding a method in my model (like Dylan's suggestion). Something like that you can reuse:
public function getAllForSelect()
{
$lang = $this->getDI()->getSession()->language;
$items = CategoriesI18n::find([
'columns' => ['foreign_key', 'title'],
'conditions' => 'lang = :lang:',
'bind' => [
'lang' => $lang
],
'order' => 'title ASC',
'cache' => ['lifetime' => 360000, 'key' => 'categories-all-for-select-'. $lang]
]);
$collection = [];
foreach ($items as $item) {
$collection[$item->foreign_key] = $item->title;
}
return $collection;
}
Why does this method build $collection
? If you're iterating through it in your view files, you can iterate through a collection as returned by find() just as easily.
@Dylan, this was just a mere example. To feed your curiosity i'm using the array for form select values, presentating db values to users (when storing ID in database, but wanna show actual title)... and so on :)