Fetching a model in 5.x

I’ve been struggling to use fetchModel() in a class. According to the information in the Book this should work:

use ModelAwareTrait;
...
class AuthorsController extends AppController
{
    public function view($slug)
    {
        $articles = $this->fetchModel('Articles');
...

But I get an undefined method error:

Call to undefined method App\Controller\AuthorsController::fetchModel()

What am I missing?

Why are you not using the directly above documented fetchTable()?

Maybe you are not fully/properly including the trait, as with the trait both should be available.
fetchTable() is the primary recommended method for loading ORM tables

  • fetchModel() requires you to explicitly add ModelAwareTrait to your
    controller first, and is intended for loading non-ORM models (Elastic,
    Webservice, etc.)

I would like to paginate the results. I may have misunderstood the docs, and thought that I needed a model to do that. After trying with fetchTable(), lit looks like paginate is generating a result set.

I do have a question while I’ve got you though. I have an author’s table with an associated articles table. On an author page I want to paginate the author’s associated articles. The controller function looks like this:

public function view($slug)
{
   $author = $this->Authors->findBySlug($slug)->contain('Articles.Tags')->firstOrFail();

    $this->set(compact('author'));
}

Is it possible to paginate contained tables, or is a separate table request necessary?

There is no CakePHP builtin method to paginate over associated records as the eager loader always loads all associated records.

If you want to display associated records in a paginated matter you will have to create a separate query instance and filter accordingly.

1 Like