2
votes

I am trying to return data from my database to JSON in Zend Framework 2. I am using a TableGateway right now and it returns a ResultSet. But the JsonModel cannot show the resultset. So is there a way to convert it, or is there an other way to access my database?

The IndexAction in the HomeController

public function indexAction()
{
    return new JsonModel(array(
        'posts' => $posts,
        'resources' => $resources,
        'style' => $style,
        'imgStyle' => $imgStyle,
        'success' => true,
    ));
}

The function that returns the resultset

public function fetchAll()
{
    $resultSet = $this->tableGateway->select(function (Select $select) {
        $select->order('date DESC');
    });
    return $resultSet;
}
2

2 Answers

3
votes

Considering you have already done this in module.config.php:

'view_manager' => array(
    'strategies' => array(
        'ViewJsonStrategy',
    ),
),

My next suggestion would be to convert the result to array.

$resultSet->toArray();

OR

$return = array();

foreach( $resultSet as $r )
    $return[]=$r;

Your return new JsonModel, is correct.

0
votes

You can use the Zend\Stdlib\Hydrator\Reflection-hydrator, either in the fetchAll method in or the Controller:

public function __construct(\Zend\Stdlib\Hydrator\Reflection $hydrator)
{
    $this->hydrator = $hydrator;
}

public function fetchAll() : array 
{
    $resultSet = $this->tableGateway->select(function (Select $select) {
        $select->order('date DESC');
    });
    $return = [];
    foreach($resultSet as $result) {
        $return[] = $this->hydrator->extract($result);
    }
    return $return;
}