" /> ">
Home Backend Development PHP Tutorial Yii2如何批量添加数据_PHP

Yii2如何批量添加数据_PHP

May 27, 2016 am 10:04 AM

批量添加这个操作,在实际开发中经常用得到,今天小编抽空给大家整理些有关yii2批量添加的问题,感兴趣的朋友一起看看吧。

在上篇文章给大家介绍了关于浅析Yii2 gridview实现批量删除教程,当然,着重点在于怎么去操作gridview了,今儿我们来好好谈谈yii2如何批量添加数据?

有同学嚷嚷了,这还不简单,我foreach一循环,每个循环里面直接把数据插入到数据库,简单粗暴完事!我擦嘞,哥,你要是跟我在一个公司,我觉得第二天见到你的概率可就不大了!

话不多说,说多了你在骂我,我们步入正题,先看一个简单到小学生都认识的表结构

//test 
id 
name
Copy after login

我们现在就是要在yii2中对这张数据表批量插入10条数据

我们想要的方式肯定是下面这样的,一条sql多么干脆直接了事

insert into test (name) values ('zhangsan'), ('lisi');
Copy after login

分析都分析完了,好吧,赶紧看看具体实现

//假如 $names = ['zhangsan', 'lisi']; 
$data = []; 
foreach ($names $k => $v) { 
$data[] = [$v]; 
} 
Yii::$app->db->createCommand()->batchInsert('test', ['name'], $data)->execute();
Copy after login

我相信很多人都是冲着AR能不能实现批量插入来的,理由无非就是更安全更方便操作呗。但是官方手册貌似没有,没有,没有。。。心都碎了,竟然没有,至少我没有找到,你找到了请点击原文找到我并联系我,我也si分的需要方法啊。

不过不巧的是,我找到一个跟AR相关联的操作方法,我们共同分享参考一下看看具体怎么回事

假设有一个Post类的数组 $models,你就可以这样操作

use yii\helpers\ArrayHelper; 
$rows = []; 
foreach ($models as $model) {
if ($model->validate()) { 
$rows[] = $model->attributes;
} 
} 
$rows = ArrayHelper::getColumn($models, 'attributes'); 
$postModel = new Post; 
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute(); 
//当然啦,上面给出的是插入所有的字段,但事实往往事与愿违,也简单,稍作调整即可 
$rows[] = [ 
'title' => $model->title, 
'content' => $model->content, 
]; 
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), ['title', 'content'], $rows)->execute();
Copy after login

虽然又回到了batchInsert上,不过没关系,该验证的都验证了,安全是无须担心的。

以上所述是小编给大家介绍的Yii2如何批量添加数据的相关知识,希望对大家有所帮助!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles