在thinkphp5.0.7版本下使用,如果用模型多次执行save操作,会提示产生的主键ID重复。代码如下
$FbPostImageModel = new FbPostImage();
for ($i=0; $i < 10; $i++) {
$data['object_id'] = rand(0, 10000);
$data['picture'] = "test";
$data['images'] = "test";
$data['link'] = "abc";
$data['caption'] = "";
$FbPostImageModel->isUpdate(false)->save($data);
}
异常提示:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '17' for key 'PRIMARY'
// 调试结束
$this->debug(false);
$this->numRows = $this->PDOStatement->rowCount();
return $this->numRows;
} catch (\PDOException $e) {
if ($this->config['break_reconnect'] && $this->isBreak($e)) {
return $this->close()->execute($sql, $bind);
}
throw new PDOException($e, $this->config, $this->getLastsql());
}
}
/**
* 根据参数绑定组装最终的SQL语句 便于调试
* @access public
* @param string $sql 带参数绑定的sql语句
* @param array $bind 参数绑定列表
* @return string
Call Stack
in Connection.php line 457
at Connection->execute('INSERT INTO `fb_post...', ['__data__object_id' => [731, 2], '__data__picture' => ['test', 2], '__data__images' => ['"test"', 2], ...]) in Query.php line 239
at Query->execute('INSERT INTO `fb_post...', ['__data__object_id' => [731, 2], '__data__picture' => ['test', 2], '__data__images' => ['"test"', 2], ...]) in Query.php line 2062
at Query->insert(['object_id' => 731, 'picture' => 'test', 'images' => '"test"', ...]) in Model.php line 934
at Model->save(['object_id' => 731, 'picture' => 'test', 'images' => 'test', ...]) in Index.php line 40
at Index->testMultiInsert()
at ReflectionMethod->invokeArgs(object(Index), []) in App.php line 224
at App::invokeMethod([object(Index), 'testmultiinsert'], []) in App.php line 389
at App::module(['Index', 'index', 'testMultiInsert'], ['app_namespace' => 'app', 'app_debug' => true, 'app_trace' => false, ...], null) in App.php line 130
at App::run() in start.php line 18
at require('/home/web/facebook_p...') in index.php line 20
生成的sql是:
INSERT INTO `fb_post_image` (`object_id` , `picture` , `images` , `link` , `caption` , `update_time`) VALUES ('8822' , 'test' , '\"test\"' , 'abc' , '' , '2017-03-09 14:47:40')
这里的17是自增主键ID。为了避免这个问题,需要将新增代码改成
$FbPostImageModel->isUpdate(false)->data($data, true)->save();
生成的sql是
INSERT INTO `fb_post_image` (`object_id` , `picture` , `images` , `link` , `caption` , `update_time`) VALUES ('7774' , 'test' , '\"test\"' , 'abc' , '' , '2017-03-09 14:48:49')
这可能是thinkphp的bug。