栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP > php开源框架 > thinkphp

ThinkPHP5中saveAll和insertAll的用法用法

thinkphp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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,制动识别新增还是保存,返回的是操作数据的对象


建议:


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/824980.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号