Cake\Database\Query::decorateResults PHP Метод

decorateResults() публичный Метод

Callbacks will be executed lazily, if only 3 rows are fetched for database it will called 3 times, event though there might be more rows to be fetched in the cursor. Callbacks are stacked in the order they are registered, if you wish to reset the stack the call this function with the second parameter set to true. If you wish to remove all decorators from the stack, set the first parameter to null and the second to true. ### Example $query->decorateResults(function ($row) { $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']); return $row; });
public decorateResults ( callable | null $callback, boolean $overwrite = false )
$callback callable | null The callback to invoke when results are fetched.
$overwrite boolean Whether or not this should append or replace all existing decorators.
    public function decorateResults($callback, $overwrite = false)
    {
        if ($overwrite) {
            $this->_resultDecorators = [];
            $this->_typeCastAttached = false;
        }
        if ($callback !== null) {
            $this->_resultDecorators[] = $callback;
        }
        return $this;
    }

Usage Example

Пример #1
0
 /**
  * Tests stacking decorators for results and resetting the list of decorators
  *
  * @return void
  */
 public function testDecorateResults()
 {
     $query = new Query($this->connection);
     $result = $query->select(['id', 'title'])->from('articles')->order(['id' => 'ASC'])->decorateResults(function ($row) {
         $row['modified_id'] = $row['id'] + 1;
         return $row;
     })->execute();
     while ($row = $result->fetch('assoc')) {
         $this->assertEquals($row['id'] + 1, $row['modified_id']);
     }
     $result = $query->decorateResults(function ($row) {
         $row['modified_id']--;
         return $row;
     })->execute();
     while ($row = $result->fetch('assoc')) {
         $this->assertEquals($row['id'], $row['modified_id']);
     }
     $result = $query->decorateResults(function ($row) {
         $row['foo'] = 'bar';
         return $row;
     }, true)->execute();
     while ($row = $result->fetch('assoc')) {
         $this->assertEquals('bar', $row['foo']);
         $this->assertArrayNotHasKey('modified_id', $row);
     }
     $results = $query->decorateResults(null, true)->execute();
     while ($row = $result->fetch('assoc')) {
         $this->assertArrayNotHasKey('foo', $row);
         $this->assertArrayNotHasKey('modified_id', $row);
     }
 }
All Usage Examples Of Cake\Database\Query::decorateResults