示例分析
//批量数据 $arr = [ ['name'=>'PHP博客1','url'=>'https://www.liqingbo.cn/','status'=>1], ['name'=>'PHP博客2','url'=>'https://www.liqingbo.cn/','status'=>2], ['name'=>'PHP博客3','url'=>'https://www.liqingbo.cn/','status'=>3], ['name'=>'PHP博客4','url'=>'https://www.liqingbo.cn/','status'=>4], ['name'=>'PHP博客5','url'=>'https://www.liqingbo.cn/','status'=>5], ];
表名:lqbcms_test
批量新增
insertAll用法
//Db的方式 $res = Db::name('tests')->insertAll($arr); //Model的方式 $res = $TestModel->insertAll($arr); //上面两种方式的返回值都是5
saveAll用法
//只能用于model中使用 $res = $TestModel->saveAll($arr); 返回的是添加后的对象 think\model\Collection Object ( [items:protected] => Array ( [0] => app\salary\model\TestModel Object ( [data] => Array ( [name] => PHP博客1 [url] => https://www.liqingbo.cn/ [status] => 1 [id] => 219 ) [relation] => Array ( ) ) [1] => app\salary\model\TestModel Object ( [data] => Array ( [name] => PHP博客2 [url] => https://www.liqingbo.cn/ [status] => 2 [id] => 220 ) [relation] => Array ( ) ) [2] => app\salary\model\TestModel Object ( [data] => Array ( [name] => PHP博客3 [url] => https://www.liqingbo.cn/ [status] => 3 [id] => 221 ) [relation] => Array ( ) ) [3] => app\salary\model\TestModel Object ( [data] => Array ( [name] => PHP博客4 [url] => https://www.liqingbo.cn/ [status] => 4 [id] => 222 ) [relation] => Array ( ) ) [4] => app\salary\model\TestModel Object ( [data] => Array ( [name] => PHP博客5 [url] => https://www.liqingbo.cn/ [status] => 5 [id] => 223 ) [relation] => Array ( ) ) ) )
总结:
1、insertAll用法和foreach循环insert的优点是带有事务处理,只要有一条失败,所以数据都插入不成功
2、insertAll可以用于Db和可以用于Model,并且返回值是插入的条数
3、saveAll只能用在model,制动识别新增还是保存,返回的是操作数据的对象
建议: