Zend-framework Query TOP

血红的双手。 提交于 2020-01-06 13:08:53

问题


Hello i try generate a query in Zend 2 just like this

 select top 10 * from mensaje where idUsuario = 11 order by fechaAltaMensaje DESC

i try use this

$select = $sql->select();
   $select->from('mensaje');
   $select->where('idUsuario = '.$idUser.' order by fechaAltaMensaje DESC');
$select->limit(5);

but don't work


回答1:


You are missing some details in your code in order for it to work,

please see below.

$adapter = $this->tableGateway->getAdapter();//use Zend\Db\TableGateway\TableGateway;
$sql = new Sql($adapter);//use Zend\Db\Sql\Sql;
$select = $sql->select();
$select->from('mensaje');
$select->where('idUsuario = '.$idUser.'');
$select->order('fechaAltaMensaje DESC');
$select->limit(5);
$selectString = $sql->getSqlStringForSqlObject($select);//print_r($selectString);die; //gives you the query in string
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
$resultSet = new ResultSet();//use Zend\Db\ResultSet\ResultSet;
$resultSet->initialize($results);
return $resultSet->toArray();//the result to array

Please read the tutorials below and you will get the full picture

Examples

Examples 2




回答2:


The limit function only applies to platforms that support it. To achieve what you're after in SQL you need to use the quantifier function.

Also - where accepts an array of column => value pairs.

And there is an order function that accepts a column name and direction:

$select = $sql->select();
$select->from('mensaje')
       ->where(['idUsuario' => $idUser])
       ->order('fechaAltaMensaje DESC')
       ->quantifier('TOP(5)')

I am not pleased with Zends implementation of the sql abstraction layer, when you need to use two different functions to write SQL that is not cross platform to do simple things like limit or top. That's just my two pence.



来源:https://stackoverflow.com/questions/23811334/zend-framework-query-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!