yii批量插入数据
现在有如下数据:
$user=array( 0=>array('id'=>1,'name'=>'张三'), 0=>array('id'=>2,'name'=>'李四'), );
现在如果需将这两条数据批量插入到数据表的话,一般大家都会想到用foreach,然后调用 insert 或者 save 方法插入数据。但实际操作却是在foreach循环操作中,insert 只会插入第一条数据,save 却只会插入第二条数据。这是为什么呢?解释如下:
插入一行到基于这个ActiveRecord的属性表。如果表的主键是自动增量和插入前为null,将插入后的实际值填充。注意,验证不执行此方法。你可以调用validate执行验证。记录成功插入到数据库后,它的isNewRecord属性将设置为false,和它的scenario属性将设置为 update。
既然如此,那么除了使用事务该如何实现数据的批量插入呢?经试验总结了如下两种方法:
第一种方法
$model=new User(); foreach($data as $attributes){ $_model=clone $model; $_model->setAttributes($attributes); $_model->save(); }
第二种方法
$model=new User(); foreach($data as $attributes){ $model->isNewRecord=true; $model->setAttributes($attributes); $model->save()&&$model->id=0; }
您可能感兴趣的文章
- Yii framework框架之模块开发分析
- Yii框架Yiiapp()的理解
- yii 数据库添加,修改,删除相关操作总结
- yii框架如何配置默认controller与action
- Yii中的数据库事务的使用方法小结
- Yii控制器动作参数绑定处理
- yii数据库查询操作总结
- yii框架缓存知识总结

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
