0

What's the correct way to limit the number of contained associated records when paginating?

The docs don't appear to address how to set options for 'contain' while paginating, but $paginate['contain']['AssociatedModel']['limit'] = 1; seemed to make sense. However, that line is resulting the following error for me in CakePHP 3.1.3:

Fatal error: Unsupported operand types in ...\vendor\cakephp\cakephp\src\ORM\EagerLoader.php on line 312

The error being generated because, in the line $pointer[$table] = $options + $pointer[$table];, $options is 1 and $pointer[$table] is an array.

Confusingly, setting $paginate['contain']['AssociatedModel']['fields'] works as expected, but setting 'limit' or 'order' results in that same error.

Phantom Watson
  • 2,667
  • 4
  • 25
  • 39

1 Answers1

1

Despite the fact that setting $paginate['contain']['AssociatedModel']['fields'] = [...] works, other options need to be set using functions. The following code fixes my problem:

$paginate['contain']['AssociatedModel'] = function($q) {
    return $q
        ->select([...])
        ->limit(1)
        ->order([...]);
};
Phantom Watson
  • 2,667
  • 4
  • 25
  • 39