Search code examples
zend-frameworkzend-db-table

Zend_Db_Table_Abstract Loading Joined Models


I have a tables named:

client (id, alias) post (id, subject) post_client (id, post_id, client_id)

Many clients can be joined to a post.

Using Zend DB Table abstract I have started to build a model, here are the classes:

ORM_Post

class ORM_Post extends Zend_Db_Table_Abstract {

    protected $_name = 'Post';
    protected $_dependentTables = array('ORM_Post_Client');

}

ORM_Client

class ORM_Client extends Zend_Db_Table_Abstract {


    protected $_name = 'Client';
    protected $_dependentTables = array(
        'ORM_Post_Client'
    );
}

ORM_Post_Client

class ORM_Post_Client extends Zend_Db_Table_Abstract {

    protected $_name = 'Post_Client';
    protected $_referenceMap    = array(
        'post' => array(
            'columns'           => 'post_id',
            'refTableClass'     => 'ORM_Post',
            'refColumns'        => 'id'
        ),
        'client' => array(
            'columns'           => 'client_id',
            'refTableClass'     => 'ORM_Post_Client',
            'refColumns'        => 'id'
        )

    );
}

What I was hoping todo is call an instance of the Post and then load the clients associated aswell as loading an instance of the client and load all posts associated.

So I did this:

    $post = new ORM_Post();
    $results = $post->fetchAll();

    foreach ($results as $key => $result){
        $row = $results->current();
        $client = $row->findDependentRowset('ORM_Post_Client','client');
    }

and I get Reference rule "client" does not reference table ORM_Post

I have battled with this for hours and cannot see where I'm going wrong. Am I to declare the Post_Client joins inside the client and post model also?

EDIT

Here is what I was after:

    $post = new ORM_Post();
$results = $post->fetchAll();
$return = array();

    foreach ($results as $result){
        $row = $post->find($result->id)->current();
        $return[$result->id] = $row->toArray();
        $return[$result->id]['clients'] = $row->findManyToManyRowset('ORM_Client', 'ORM_Post_Client')->toArray();
}

return $return;

Thanks for the advice guys, you put me on the right track


Solution

  • in your ORM_Post_Client it should be

    'client' => array(
                'columns'           => 'client_id',
                'refTableClass'     => 'ORM_Client',  //instead of ORM_Post_Client 
                'refColumns'        => 'id'
            )
    

    refTableClass => The class name of the parent table. Use the class name, not the physical name of the SQL table (documentation)

    also i think your loop should be :

    foreach ($results as $result){
            $row = $results->current();
            $clients = $row->findDependentRowset('ORM_Post_Client','post'); 
      }
    

    because you are looking for clients of a post which means that post is your rule

    ($row->findDependentRowset($table, [$rule]); )