yii2批量插入数据与查询大量数据使用batch和each省内存

 $userkey=['login','password','nicename','email','create_time'];//测试数据键
    
   $uservale=array(
        '0'=>array('admin2','2b571c42c2d79deb9872aeb0befc0124','admin','[email protected]','2017-07-21 15:47:07'),
        '1'=>array('admin1','2b571c42c2d79deb9872aeb0befc0124','admin','[email protected]','2017-07-21 15:47:07'),
        '2'=>array('admin55','2b571c42c2d79deb9872aeb0befc0124','admin','[email protected]','2017-07-21 15:47:07'),
        '3'=>array('admin66','2b571c42c2d79deb9872aeb0befc0124','admin','[email protected]','2017-07-21 15:47:07'),
    );//测试数据值

   $res= \Yii::$app->db->createCommand()->batchInsert(Users::tableName(), $userkey, $uservale)->execute();//执行批量添加


$sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
    ['Tom', 30],
    ['Jane', 20],
    ['Linda', 25],
]);



$model = new User();
foreach($data as $attributes)
{
      $model->isNewRecord = true;
      $model->setAttributes($attributes);
      $model->save() && $model->id=0;

}

$model = new User();
foreach($data as $attributes)
{
     $_model = clone $model;
     $_model->setAttributes($attributes);
     $_model->save();
}

当我们遇到需要一次读取出所有的或是大批量数据的时候,可以考虑使用batch和each,这一点点代码的优化帮你省掉了一半的内存。
$query = new \yii\db\Query();
$query->from('user');
foreach($query->batch() as $users){
        foreach($users as $user){
        echo $user['username'];
        echo "
"; } } $query = new \yii\db\Query(); $query->from('user'); foreach($query->each() as $user){ echo $user['username']; echo "
"; }


memory_get_usage();查看当前内存


你可能感兴趣的:(yii2)