Thinkphp中的Model操作有两个方法:add()和addAll
<span><span>1</span> <span>$User</span> = M("User"); <span>//</span><span> 实例化User对象</span> <span>2</span> <span>$data</span>['name'] = 'ThinkPHP'<span>; </span><span>3</span> <span>$data</span>['email'] = 'ThinkPHP@gmail.com'<span>; </span><span>4</span> <span>$User</span>->add(<span>$data</span><span>); </span><span>5</span> <span>6</span> <span>$dataList</span>[] = <span>array</span>('name'=>'thinkphp','email'=>'thinkphp@gamil.com'<span>); </span><span>7</span> <span>$dataList</span>[] = <span>array</span>('name'=>'onethink','email'=>'onethink@gamil.com'<span>); </span><span>8</span> <span>$User</span>->addAll(<span>$dataList</span>);</span>
addAll方法可以做到批量添加数据的功能,也就是MySQL的这种用法:
<pre name="code" class="sql"><span>INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);</span>
数据量很多情况下尽量选择批量插入而不是循环逐条插入,否则你的数据库会吃不住挂掉。
不过如果你想当然的将所有数据全部存入一个数组并进行addAll也同样会面临挂掉的情况,这是为什么呢?
原因就是mysql中max_allowed_packet变量的配置限制了上传sql语句的长度,在mysql配置中将他配置大一点就行了
<pre name="code" class="plain"><span>max_allowed_packet = 100M</span>
同时在插入数据时也做好批量插入的长度限制,毕竟你不知道什么时候数据会变成百万级别的。