phpsqlselectzend-framework2rowset

Select a Row from a RowSet in ZF2


My table looks something like this

    id      uniqueId    userId  album
    1       1           1       Example
    2       2           1       Example
    3       1           2       Example
    4       3           1       Example
    5       2           2       Example

I would like to find the Album Title where userId => 1 and uniqueId => 3 (Where id => 4, but I won't have access to that, only the other two).

To do this I am attempting to getAlbumsByUserId($userId) which will return a RowSet object with User 1's Albums. Then I am trying to get the album from the returned rowset with uniqueId => 3

Something like the below won't work
$albumObject = $albumTable->getAlbumsByUserId(1);
$row = $albumObject->select(array('uniqueAlbumID' => 3))->current();

This is the function which gets Albums by UserId as a RowSet

public function getAlbumsByUserId($userId)
    {
        $userId     = (int) $userId;
        $rowset = $this->tableGateway->select(array('user_id' => $userId));

        return $rowset;
    }

I could do a foreach on the RowSet object, to find the uniqueId with an if statement, but I have to think there is a better way.

Edit:
I still haven't found a way to do a select from resultSet, but you can do 2 where conditions in the select array.


Solution

  • Maybe i don't understand what do you want exactly but how about making your query statement with join you have nice set of functions to accomplish that in Zend.

    In your AlbumTable.php:

    public function getAlbum($userId, $uniqueAlbumId){
        $resultSet = $this->tableGateway->select()->where(array('userId = 1', 'uniqueId = 3'));
        $row = $resultSet->current();
        if(!$row){
             throw new Exception('No row found');
       }
        return $row;
    }