環境
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
);