ThinkPHP5中saveAll和insertAll的用法

示例分析

//批量数据
$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);

返回的是添加后的对象
thinkmodelCollection Object ( [items:protected] => Array ( [0] => appsalarymodelTestModel Object ( [data] => Array ( [name] => PHP博客1 [url] => https://www.liqingbo.cn/ [status] => 1 [id] => 219 ) [relation] => Array ( ) ) [1] => appsalarymodelTestModel Object ( [data] => Array ( [name] => PHP博客2 [url] => https://www.liqingbo.cn/ [status] => 2 [id] => 220 ) [relation] => Array ( ) ) [2] => appsalarymodelTestModel Object ( [data] => Array ( [name] => PHP博客3 [url] => https://www.liqingbo.cn/ [status] => 3 [id] => 221 ) [relation] => Array ( ) ) [3] => appsalarymodelTestModel Object ( [data] => Array ( [name] => PHP博客4 [url] => https://www.liqingbo.cn/ [status] => 4 [id] => 222 ) [relation] => Array ( ) ) [4] => appsalarymodelTestModel 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,制动识别新增还是保存,返回的是操作数据的对象

建议:

温馨提示: 本文最后更新于2024-12-31 21:08:53,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系 蚂蚁官方
© 版权声明
THE END
喜欢就支持一下吧
点赞14赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容