2017-02-27 86 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()