Search code examples
phprestapidoctrine-ormzend-framework2

Doctrine findby to loop all through rows to show all users


I'm very new to PHP and having trouble making an API that's essentially taking a GET request and returning all users stored in a table. This application uses Zend Framework 2 and Doctrine.

Controller:

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);
}

Model:

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;
    }
}

At the moment I can successfully retrieve data and return it via rest, but only the first set(row) of data. There are more in the table with the same business ID.

How to I return all rows that have the same business ID instead of just the first one? Thank you!


Solution

  • The problem is in your loop in findAllByBusinessID method. return breaks your loop, so only first row is returned. What do you want is probably something like this:

    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;
    }
    

    But you should split this method into 2 separate functions. One function for retrieving data from database, one to format data the way you want.

    Another solution would be to use Doctrine's queryBuilder and return data as array set (getArrayResult())