ActiveRecord的批量插入(yii2) [英] ActiveRecord batch insert (yii2)

查看:1921
本文介绍了ActiveRecord的批量插入(yii2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,是不是可以插入多行的一个查询与ActiveRecord的,或者最好使用DAO此?

So, is it possible to insert multiple rows in one query with ActiveRecord, or it's better to use DAO for this?

推荐答案

您可以使用 batchInsert()法警予\ DB \命令。查看详情这里。 当与的ActiveRecord 使用它插入之前备份所有数据,确保验证。

You can use batchInsert() method of yii\db\Command. See details here. When using it with ActiveRecord make sure validate all data before inserting.

假设你有$车型数组类发表,它可以这样做:

Assuming you have array of $models with class Post, it can be done like this:

$rows = [];
foreach ($models as $model) {
    if (!$model->validate()) {
        // At least one model has invalid data

        break;
    }

    $rows[] = $model->attributes;
}

如果模式不要求验证即可做空code以上使用 ArrayHelper 建筑 $行阵列。

If models don't require validation you can short the code above using ArrayHelper for building $rows array.

use yii\helpers\ArrayHelper;

$rows = ArrayHelper::getColumn($models, 'attributes');

然后只需执行批量插入:

Then simply execute batch insert:

$postModel = new Post;

Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();

P.S。该 $ postModel 只是用于拉attirubute名称列表中,您还可以在$车型阵列完成这从任何现有的$模式。

P.S. The $postModel just used for pulling attirubute names list, you can also pull this from any existing $model in your $models array.

如果您不需要插入所有的属性,你可以在填充时指定它 $行数组:

If you don't need to insert all attributes you can specify it when filling $rows array:

$rows[] = [
    'title' => $model->title,
    'content' => $model->content,
];

不要忘了替换 $ postModel->属性 ['标题','内容']

在的情况下更大的属性,你可以使用一些阵列功能,以指定确切属性插入量。

In case of larger amount of attributes you can use some array functions to specify exact attributes for inserting.

这篇关于ActiveRecord的批量插入(yii2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆