LoginSignup
4
4

More than 5 years have passed since last update.

CakePHP3でモデルのbeforeSaveを利用してidをインクリメントする

Last updated at Posted at 2017-05-02

システムの仕様上、DBでidの値をオートインクリメントすることができない。

そんな時にCakePHP3でモデルのbeforeSave()を利用してidをインクリメントさせる。

public function beforeSave($event, $entity, $options) {
    $query = $this->_table->find();
    $ret = $query->select(['max_id' => $query->func()->max('id')])->first();
    if($entity->isNew()) {
        $entity->set('id', $ret['max_id'] +1);
    }
}

$entity->isNew() でレコードを追加する場合のみ動作するようにする。

4
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
4
4