Search code examples
cakephpormfindclause

Cake PHP 3 needs limit option for find all method


Inside a cell I need to access the TreeOptions model. So I've wrote this :

    $this->loadModel( 'TreeOptions' );

    $i = $this->TreeOptions->find( 'all' );

But when I do the foreach like this :

    foreach( $i as $row )
      debug( $row->description );

It only returns the last record of the result. The only way I've found to make it work as desired is adding the limit clause :

     $i = $this->TreeOptions->find( 'all', [ 'limit' => 200 ] );

And then, I can get the whole set of records. What am I missing ?

Thanks. Regards.


Solution

  • In your first snippet, the variable $i, is a state where the query has not yet run. See the excerpt from CakePHP 3 Cookbook: Retrieving Data & Results — Using Finders to Load Data:

    // Find all the articles.
    // At this point the query has not run.
    $query = $articles->find('all');
    
    // Iteration will execute the query.
    foreach ($query as $row) {
    }
    
    // Calling all() will execute the query
    // and return the result set.
    $results = $query->all();
    
    // Once we have a result set we can get all the rows
    $data = $results->toArray();
    
    // Converting the query to an array will execute it.
    $results = $query->toArray();