LoginSignup
0
0

More than 3 years have passed since last update.

🍰【CakePHP2】バルクインサート失敗するときは対象カラムを確認する

Last updated at Posted at 2020-02-23

環境

PHP 7.2.21
CakePHP 2.10.18
MySQL 5.7.27

やりたいこと

ModelのinsertMulti()関数を使い、
配列の内容から複数件インサートを行う際に次のエラーが出たので対応した

error.log
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
error.log
                            [0] => `{schema名}`.`{table名}`
                            [1] => `id`, `hoge_fuga`, `foo_bar`, `toto`, `pippo`, `xyzzy`
                            [2] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 0609045000
                                            [hoge_fuga] => 1123
                                            [new_column] => 1
                                            [foo_bar] => 202002
                                            [toto] => 2020-01-01
                                            [pippo] => 9999991
                                            [xyzzy] => Q-2
                                        )

やったこと

insertMultiの第2引数が対象カラムで第3引数がインサートする値配列
この2つにあるカラムが合っていないと↑のエラーが発生するので見直して修正する

HogeController.php
            $hogeItems[] = [
                'id'         => $id,
                'hoge_fuga'  => $hogeFuga,
                'new_column' => $newColumn, 
                'foo_bar'    => $fooBar,
                'toto'       => $toto,
                'pippo'      => $pippo,
                'xyzzy'      => $xyzzy,
            ];

            // 🔵それぞれのカラムが合致
            // バルクインサートする
            $this->HogeModel->getDataSource()->insertMulti(
                '{table名}',
                ['id' , 'hoge_fuga', 'new_column', 'foo_bar', 'toto', 'pippo', 'xyzzy'],
                $hogeItems
            );

            // ❌それぞれのカラムが揃っていない(↑のエラーの状態)
            // バルクインサートする
            $this->HogeModel->getDataSource()->insertMulti(
                '{table名}',
                ['id' , 'hoge_fuga', 'foo_bar', 'toto', 'pippo', 'xyzzy'],
                $hogeItems
            );
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