SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row
出错原因如下:问题出在数组里各条记录的字段数量不一致,insertAll 批量插入要求每行字段完全一致。
我得原型打印数据为:
array ( 0 => array ( 'order_id' => 3, 'order_sn' => 'wxp179013551932881073', 'user_info' => '1505783', 'user_id' => 3, 'financial_type' => 'presell', 'financial_pm' => 1, 'type' => 2, 'number' => '1768.00', 'mer_id' => 4, 'financial_record_sn' => 'jy1790147464269874001', ), 1 => array ( 'order_id' => 3, 'order_sn' => 'wxo1790135519324440001', 'user_info' => '1505783', 'user_id' => 3, 'financial_type' => 'mer_presell', 'financial_pm' => 1, 'type' => 0, 'number' => '1888.00', 'mer_id' => 4, 'financial_record_sn' => 'jy1790147464269874002', ), 2 => array ( 'order_id' => 3, 'order_sn' => 'wxo1790135519324440001', 'user_info' => '1505783', 'user_id' => 3, 'financial_type' => 'brokerage_one', 'financial_pm' => 0, 'type' => 1, 'number' => '1321.59', 'mer_id' => 4, 'financial_record_sn' => 'jy1790147464269874003', 'pay_type' => 0, ), 3 => array ( 'order_id' => 3, 'order_sn' => 'wxo1790135519324440001', 'user_info' => '1505783', 'user_id' => 3, 'financial_type' => 'presell_true', 'financial_pm' => 1, 'type' => 2, 'number' => '566.41', 'mer_id' => 4, 'financial_record_sn' => 'jy1790147464269874004', 'pay_type' => 0, ), )
看数组:
第 1、2 条(索引 0、1):
order_id / order_sn / user_info / user_id / financial_type / financial_pm / type / number / mer_id / financial_record_sn,共 10 个字段第 3、4 条(索引 2、3):多了一个
pay_type,共 11 个字段
insertAll 会以第一条的字段作为列名生成一条多行 INSERT,第 3 行开始多了 pay_type 这个值,值和列对不上,所以 MySQL 报 Column count doesn't match value count at row 3(正好对应第 3 条记录)。
修复
插入前把字段统一补齐即可,比如给所有记录都补上 pay_type:
$finance = array_map(function ($item) {
return $item + ['pay_type' => 0]; // 只补缺失的键,已有键保留
}, $finance);如果字段比较多、想更稳妥,可以定义一份完整的默认字段表再合并:
$defaults = [ 'order_id' => null, 'order_sn' => null, 'user_info' => null, 'user_id' => null, 'financial_type' => null, 'financial_pm' => null, 'type' => null, 'number' => null, 'mer_id' => null, 'financial_record_sn' => null, 'pay_type' => 0, ]; $finance = array_map(fn($item) => array_merge($defaults, $item), $finance);
