Cake PHP - How to access a special Model found by

2019-07-31 18:18发布

问题:

I have the following Code to get a special model related to another model related to actual object: (I want the Entry-model - in the Rubric-model-view)

$this->paginate = array(
            'Entrieslocation' => array(
                'conditions' => array('Entrieslocation.rubric_id' => $this->Rubric->id, 'Entrieslocation.subrubric_id' => '0'),
                'joins' => array(
                    array(
                        'alias' => 'Entry',
                        'table' => 'entries',
                        'type' => 'INNER',
                        'conditions' => 'Entry.id = Entrieslocation.entry_id'
                    )
                )
            )
        );

Then I thought I could get it by something like this:

$this->set('entries', $this->paginate('Entry'));

But the variable is empty, how can I access the Entries inside the Pagination in the view?

The Query generated by the code above is correct, I checked it by entering the query into phpmyadmin. So how can I access the result (only the Entries)?

Thanks for your help :)

回答1:

First of all you must define $paginate variable below controller class. For example

class UsersController extends AppController {

     public $paginate = array();

}

Then in your action follow following patter to get the paginated result.

$this->paginate = array(
            'recursive' => -1,
            'limit' => 10,
            'conditions' => array('Your conditions'),
            'fields'     => array('Entry.*, Entrieslocations.*'),
            'joins' => array(
                array(
                  'table' => 'Entrieslocations',
                  'alias' => 'Entrieslocation',
                  'type' => 'inner',
                  'conditions' => 'Entry.id = Entrieslocation.entry_id'
                 ),
            ), 
            'order' => array(
                'Entry.id' => 'desc'
            )

        );


$entries = $this->paginate('Entry');

To pass result set to the view use following:

$this->set('entries', $entries);