- Hello, I have an array of query results that I want to be paginated. But somehow I got an error that says :
Unable to locate an object compatible with paginate.
Here’s my current code:
$this->paginate = ['limit' => 10];
$comment = TableRegistry::get('Comments');
$comments = $comment
->where(['Comments.post_id' => $id])
->order(['Comments.created' => 'ASC'])
->toArray(); //the results will be array
$comments = $this->paginate($comments);
- My second question is, is there a way to always have an array result instead of object results when having a query in the controller so that I won’t need to include ->toArray() into my code?
The error thrown says it all: you CANNOT paginate an array. You paginate Query Objects.
When you make a query, it is not executed. I mean, It does not make any SQL Queries yet so you save memory and time.
By using ->toArray() you are executing that SQL Query and making an array with ALL results that might be millions.
The point of paginating is to only retrieve the first 20 rows (for example) and only query the next 20 if they are needed.
Why do you need an array?
Answering your second question (I don’t know if you actually need it after my first answer):
You have to override find() method in a Table or in a Behavior and add ->toArray() there. But that’s totally NOT RECOMMENDED!
PS: You should call your TableRegistry variable something like $commentsTable or you could overwrite that by mistake inside a foreach $comments as $comment or something…