2

I'm using cakePHP 3.0 for back-end API. This is my code.

namespace App\Controller;

use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
use App\Controller\AppController;
use Cake\Routing\Router;

class MainController extends AppController {

   public function myMethod() {
       $groupRegistry = TableRegistry::get('MyModel');
       $query = $groupRegistry->query();
       $params = $this->request->data;

       $return = $query->update()
               ->set(['my_flag' => $params['flag']])
               ->where(['id' => $params['id']])
               ->execute();

       if (empty($return)) {
           return $this->outStatusJson('ERR100', 'Error Updating.');
       }

     return $this->outStatusJson('0', 'OK');
  }
}

I cannot track the responce of $query->update()

Any help will save my day.

2 Answers2

5

Query::execute() will return a statement object that implements \Cake\Database\StatementInterface, and thus exposes a rowCount() method that returns the number of rows affected by the statement.

So you can simply do:

$affectedRows = $return->rowCount();

And there's also the Table::updateAll() method which you could use instead, it does exactly what you're doing there (+ closing the cursor), and will return the number of affected rows.

$affectedRows = $groupRegistry->updateAll(
    ['my_flag' => $params['flag']],
    ['id' => $params['id']]
);

See also

ps

I hope you know what you are doing there, when using low level queries, your data is not going to be validated, and model save events are not being triggered!

ndm
  • 59,784
  • 9
  • 71
  • 110
0

Use the model method getAffectedRows() as described in the cakephp documentation.

As per document: Model::getAffectedRows() - Returns the number of rows affected by the last query.

Update2: ( try this )

public function getAffectedRows() {
    // Returns the number of rows affected by the last query
    //return $this->getDataSource()->lastAffected();

      $db =& ConnectionManager::getDataSource($this->useDbConfig);
      return $db->lastAffected();
}
Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33