今天早些时候,我问了一个关于更新查询的问题。但现在我想选择一些东西(并且它正在工作)但我也想订购它们并限制它。
这是选择所有食物的代码:
public function getFood($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('kindOfFood_id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
但我怎么能这样做:
从KindOfFood中选择* ==> by kindOfFood_votes DESC?
我在文档上看到你可以做这样的事情,但它不适用于我?
$rowset = $artistTable->select(function (Select $select) {
$select->where->like('name', 'Brit%');
$select->order('name ASC')->limit(2);
});
答案 0 :(得分:1)
您是否希望仅返回单行或多行。
尝试多行 -
use Zend\Db\Sql\Select; //at the top of the page among other use statements.
public function getFood($id)
{
$id = (int) $id;
$select = new Select(TABLE_NAME); //CHANGE TABLE_NAME as per needs
$select->where('kindOfFood_id = ' . $id);
$select->order('kindOfFood_votes DESC');
$resultSet = $this->tableGateway->selectWith($select); //Will get array of rows.
//$row = $rowset->current(); THIS IS FOR RETURNING ONLY SINGLE ROW NOT ALL ROWS
if (!$resultSet) {
throw new \Exception("Could not find rows with food id - $id");
}
return $resultSet;
}
可以通过循环访问返回的resultSet。例如:foreach
foreach($resultSet as $row) {
echo $row->kindOfFood_id; //or something
}
注意:
如果只需要
Select * from KindOfFood order by kindOfFood_votes DESC
然后从上方删除$select->where('kindOfFood_id = ' . $id);
行。