LoginSignup
0
0

More than 3 years have passed since last update.

Cakephpでid(auto_increment)を指定してInsert

Last updated at Posted at 2019-05-10

ネットにあまり情報が無かったので残しておきます。PHP5.3のCakephp2.10.6という古い環境ですが、恐らく、Cakephp3.xも同じかと思います(試してません)。
テーブルので主キーの物理名はidでauto_incrementになっていることを想定しています。

idを指定して登録する

public $uses = array("ModelName");

public function index() {
    $data = array();
    $data['ModelName']['id'] = 100;

    $this->ModelName->create();
    $this->ModelName->save($data);
}

単純にidに未登録の値をセットしてsaveメソッドで登録すればそのidでInsertされます。
createメソッドは必要なのかちょっと不明です。無くても登録されますが、ネットの情報だとやっておいたほうがいいとのこと。

saveメソッドでinsertかupdateかの判定は、モデルの主キー(id)がセットされている場合、その主キーで1回検索を行って取得できるかどうかで行っています(Model.phpのexistsメソッド)。ですので、未登録のidならそのままInsertされます。

Model.php
2894    public function exists($id = null) {
2895        if ($id === null) {
2896            $id = $this->getID();
2897        }
2898        if ($id === false) {
2899            return false;
2900        }
2901        if ($this->useTable === false) {
2902            return false;
2903        }
2904        return (bool)$this->find('count', array(
2905            'conditions' => array(
2906                $this->alias . '.' . $this->primaryKey => $id
2907            ),
2908            'recursive' => -1,
2909            'callbacks' => false
2910        ));
2911    }

CakePHP: Insert record with specific id

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