Search code examples
phpzend-frameworkzend-db-select

How to join two tables in Zend and read the resulting data


I have the following query:

$usersTable = new Users();

$rowset = $usersTable->select()
    ->setIntegrityCheck(false)
    ->where( 'id = ?', $userId )
    ->join( 'Books', 'Books.userid = Users.id' );

However, I can't for the life of me figure out how to read the resulting rowset (the list of books associated with the user).

Would I do the following?

foreach ($book in $rowset->Books) {
    print_r($book["book_name"]);
}

Solution

  • What you call $rowset is actually an sql expression. This should work:

    $usersTable = new Users();
    
    $sql = $usersTable->select()
        ->setIntegrityCheck(false)
        ->where( 'id = ?', $userId )
        ->join( 'Books', 'Books.userid = Users.id' );
    $rowset = $usersTable->getAdapter()->fetchAll($sql);