Converting Nette Database Selection to Array
- TheOtherGuy
- Member | 27
Hi,
is there some easy way to convert NDBT selection to array so that the result can be sent in a JSON response ?
For example i have this function:
public function getAll()
{
return $this->database->table($this->entityMainTable)->where([$this->deleted => false])->order('id' . ' DESC');
}
and this handle in presenter to send the JSON response
public function actionFeedMe() {
$this->payload->data = $this->portfolioManager->getAll();
$this->sendPayload();
}
I found several ways to do this by creating a function that'll parse the result but this solution seems to be too heavy and i'm wondering if there is not a better way to code this.
- petr.pavel
- Member | 535
I believe payload can be a traversable object as well – i.e. NDB
result.
I don't think you need to convert it to an array.
Internally, json_encode() is called and it accepts “any type except a resource”.
If you insist though, I believe fetchAssoc() is what you're looking for.
- TheOtherGuy
- Member | 27
I tried to send the selection object as payload but, it's empty in browser :/ fetchAssoc() should work, i'll try that.
- dnd
- Member | 16
Hey, but there is no ->fetchAssoc() on NDB result //Nette\Database\Table\Selection/, isn't it?
I have to do this
$data = array();
foreach($this->repositoryItem->findAll() as $r){
$data[] = $r->toArray();//*on ActiveRow*/
}
$this->sendJson($data);
instead of this
$data = $this->repositoryItem->findAll()->fetchAssoc();
$this->sendJson($data);
So, please how?
- ondrejsotek
- Member | 5
I'm using iterator_to_array() for converting Nette\Database\Table\Selection to array.