2017-02-27 88 views
-1

我對PHP很陌生,無法制作基本上接受GET請求並返回存儲在表中的所有用戶的API。這個應用程序使用Zend Framework 2和Doctrine。Doctrine findby遍歷所有行以顯示所有用戶

控制器

public function viewAllAction(){ 
    $restService = $this->getServiceLocator()->get("Rest"); 
    $restService->auth(); 
    $business = $restService->getIdentity(); 
    $bizID = $business->getId(); 

    $clientModel = $this->getServiceLocator()->get('clientModel'); 
    $clients = $clientModel->findAllByBusinessID($bizID); 
    $params['client'] = array(
     "name" => $clients->getName(), 
     "email" => $clients->getEmail(), 
     "phone" => $clients->getPhone(), 
     "address" => $clients->getAddress(), 
     "suburb" => $clients->getSuburb(), 
     "postcode" => $clients->getPostcode(), 
     "state" => $clients->getState(), 
     "country" => $clients->getCountry(), 
    ); 
    return $restService->send($params); 
} 

型號

public function findAllByBusinessID($business_id){ 
    $clientRepository = $this->getMapper()->getRepository(self::ENTITY_CLASS); 
    $clients= $clientRepository->findBy(array("bid" => $business_id)); 

    foreach($clients as $client) { 
     return $client; 
    } 
} 

此刻,我能成功地檢索數據,並通過休息恢復,但只有第一組(行)數據。表中有更多的商業ID。

如何返回所有具有相同業務ID而不是第一個行的行?謝謝!

回答

1

問題出在你的循環中findAllByBusinessID方法。 return打破了你的循環,所以只返回第一行。你想要的可能是這樣的:

public function findAllByBusinessID($business_id){ 
    $clientRepository = $this->getMapper()->getRepository(self::ENTITY_CLASS); 
    $clients= $clientRepository->findBy(array("bid" => $business_id)); 

    $results = []; 
    foreach($clients as $client) { 
     $results['client'][] = [ 
      "name" => $client->getName(), 
      "email" => $client->getEmail(), 
      "phone" => $client->getPhone(), 
      "address" => $client->getAddress(), 
      "suburb" => $client->getSuburb(), 
      "postcode" => $client->getPostcode(), 
      "state" => $client->getState(), 
      "country" => $client->getCountry(), 
     ]; 
    } 

    return $results; 
} 

但是你應該把這個方法分成2個獨立的函數。一種用於從數據庫中檢索數據的功能,一種用於按照需要的方式格式化數據。

另一種解決方案將是使用Doctrine's queryBuilder和返回數據作爲陣列組(getArrayResult()