2014-07-09 77 views
1

今天早些時候問了一個關於更新查詢的問題。但是現在我想選擇一些東西(它正在工作),但我也想要訂購它們並對其進行限制。訂單和限制在選擇查詢zend框架2

這是代碼選擇所有的食物:

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_votes DESC

SELECT * FROM KindOfFood ==>訂單?

我在文檔中看到過你可以做這樣的事情,但它不適用於我?

$rowset = $artistTable->select(function (Select $select) { 
    $select->where->like('name', 'Brit%'); 
    $select->order('name ASC')->limit(2); 
}); 
+0

如果您只需要'從KindOfFood ==選擇*> orderOfFood_votes DESC',然後從答案中刪除'$ select-> where('kindOfFood_id ='。$ id);'行。 –

回答

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; 

}

可以通過循環訪問返回的結果集。例如:的foreach

foreach($resultSet as $row) { 
    echo $row->kindOfFood_id; //or something 
} 

注:

如果您只需要

Select * from KindOfFood order by kindOfFood_votes DESC

然後從上面取下$select->where('kindOfFood_id = ' . $id);線。

+0

非常感謝,它幫了我很多。 – KimberlyGS