我是PHP的新手,无法制作一个基本上接受GET请求并返回存储在表中的所有用户的API。该应用程序使用Zend Framework 2和Doctrine。
控制器:
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的所有行,而不仅仅是第一行?谢谢!
答案 0 :(得分: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;
}
但是你应该将这个方法分成两个独立的函数。一个用于从数据库中检索数据的功能,一个用于按照您希望的方式格式化数据。
另一种解决方案是使用Doctrine's queryBuilder并将数据作为数组(getArrayResult()
)返回