Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

To use the PaginatedSqlIterator, instantiate it with the Model to query, along with conditions, fields, and contains parameters as appropriate. Then simply use the iterator in a foreach() loop.

The iterator can also obtain a record count for progress calculation purposes. For performance reasons, the record count is only updated when explicitly asked.

Code Block
languagephp
App::uses("PaginatedSqlIterator", "Lib");

class myClass {
  public function doSomething() {
    $iterator = new PaginatedSqlIterator(
      // Model to query
      'CoPerson',
      // Condition
      array('CoPerson.co_id' => $coId),
      // Fields, or null to retrieve all fields
      array('CoPerson.id', 'CoPerson.status'),
      // Contains for associated models, or null
      array('EmailAddress')
    );

    // Initial record count
    $total = $iterator->count();
    $i = 0;

    foreach($iterator as $k => $v) {
      // Do something for this particular record

      ...

      // Every 1000 records, refresh the count just in case new records have been added.
      // Note this is for informational purposes for the calling code *only*, and is not
      // required. The iterator will correctly retrieve subsequently added records
      // regardless of whether or not count() is called.
      if($i % 1000 == 0) {
        $total = $iterator->count(true);
      }
    }
  }
}