yii批量插入数据
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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Use ddrescue to recover data on Linux

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation!

How to use Excel filter function with multiple conditions

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training

Slow Cellular Data Internet Speeds on iPhone: Fixes

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times.

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training
