Doctrine findby 遍历所有行以显示所有用户

Doctrine findby to loop all through rows to show all users

我是 PHP 的新手,在制作一个 API 时遇到了麻烦,该 API 本质上是接收 GET 请求并 return 存储在 table 中的所有用户。此应用程序使用 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;
    }
}

目前我可以通过休息成功检索数据并 return 它,但只有第一组(行)数据。 table 中还有更多具有相同商家 ID 的商家。

如何 return 所有具有相同业务 ID 的行,而不仅仅是第一行?谢谢!

问题出在 findAllByBusinessID 方法的循环中。 return 打破了你的循环,所以只有第一行是 returned。你想要的大概是这样的:

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 和 return 数据作为数组集 (getArrayResult())