LoginSignup
3
4

More than 3 years have passed since last update.

CakePHPのsaveメソッドがupdateにならない場合

Last updated at Posted at 2017-10-11

1.更新するテーブルのプライマリキーがセットされているか確認する。

$this->MODEL_NAME->id = $primary_id;

2.実行されたSQLログを取得する。

try {
    $result = $this->MODEL_NAME->save($data);
} catch (PDOException $e) {
    $this->log('DBerror:' . $e->getMessage(), LOG_DEBUG);
}

$this->log($this->MODEL_NAME->getDataSource()->getLog(), LOG_DEBUG);

$this->logで /app/tmp/logs/debug.log にログが書き出される。
書き出されない場合は、core.phpのdebug設定が2になっているか確認。

app/config/core.php
/**
 * CakePHP Debug Level:
 *
 * Production Mode:
 *  0: No error messages, errors, or warnings shown. Flash messages redirect.
 *
 * Development Mode:
 *  1: Errors and warnings shown, model caches refreshed, flash messages halted.
 *  2: As in 1, but also with full debug messages and SQL output.
 *
 * In production mode, flash messages redirect after a time interval.
 * In development mode, you need to click the flash message to continue.
 */
    Configure::write('debug', 2);

3.モデル内で、function exists(){}がオーバーライドされていないか確認する。
通常は、継承元のAppModelの中にあるexists(){}でプライマリキーを条件にしたSELECT文が作成される。
しかし、下記のようなプライマリキー以外の条件を追加したコードが継承したモデル内にあると、SELECT文の条件が変わってしまい別レコードとして処理されてしまう。

public function exists($id = null)
{
    if ($id === false) {
        return false;
    }

    return (bool)$this->find('count', array(
        'conditions' => array(
            $this->alias . '.' . $this->primaryKey => $id,
            $this->alias . '.public_flag' => 1
        ),
        'recursive' => -1,
        'callbacks' => false
    ));
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4