Yii:在一个查询中保存多条记录

olqngx59  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(282)

我尝试在循环中保存大量CActiveRecord模型对象。我有这样的代码:

foreach ($array_of_items as $item) {

    $values = array(
        "title"   => $item->title,
        "content" => $item->content,
    );

    $object = new MyModel;
    $object->attributes = $values;
    $object->save();

}

在我的例子中,这将创建大约400个CActiveRecord对象。保存过程非常慢,因为每个**保存()**都要查询数据库。
是否有一种方法可以一次性保存所有这些对象?例如:

$objects = array();

foreach ($array_of_items as $item) {

    $values = array(
        "title"   => $item->title,
        "content" => $item->content,
    );

    $object = new MyModel;
    $object->attributes = $values;
    $objects[] = $object;
}

save_all_objects($objects);

我找不到任何关于这个主题的东西。有人吗?

iq3niunx

iq3niunx1#

您可以对模型执行validate()操作,如果可以,您可以将其附加到sql文本中以进行插入,
在循环之后,只需使用数据库commandBuilder()并执行准备好的文本

$sql = '';
if($object->validate())
{
    $sql .= ',("' . $object->attr1 . '")'// append to script,(you get the idea, you need to also make a correct values)
}

...

if(!empty($sql))
{
    $sql = 'INSERT INTO table (attr1) Values' . $sql;// make complete script
    // execute that command
}
qqrboqgw

qqrboqgw2#

自v1.1.14起,CDbCommandBuilder类的方法createMultipleInsertCommand()可用。

6jygbczu

6jygbczu3#

对于插入多行,将此代码放在GeneralRepository.php文件名下components文件夹中

<?php
class GeneralRepository
{
    /**
     * Creates and executes an INSERT SQL statement for several rows.
     * By: Nabi K.A.Z. <www.nabi.ir>
     * Version: 0.1.0
     * License: BSD3
     * 
     * Usage:
     * $rows = array(
     *      array('id' => 1, 'name' => 'John'),
     *      array('id' => 2, 'name' => 'Mark')
     * );
     * GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
     * 
     * @param string $table the table that new rows will be inserted into.
     * @param array $array_columns the array of column datas array(array(name=>value,...),...) to be inserted into the table.
     * @return integer number of rows affected by the execution.
     */
    public static function insertSeveral($table, $array_columns)
    {
        $connection = Yii::app()->db;
        $sql = '';
        $params = array();
        $i = 0;
        foreach ($array_columns as $columns) {
            $names = array();
            $placeholders = array();
            foreach ($columns as $name => $value) {
                if (!$i) {
                    $names[] = $connection->quoteColumnName($name);
                }
                if ($value instanceof CDbExpression) {
                    $placeholders[] = $value->expression;
                    foreach ($value->params as $n => $v)
                        $params[$n] = $v;
                } else {
                    $placeholders[] = ':' . $name . $i;
                    $params[':' . $name . $i] = $value;
                }
            }
            if (!$i) {
                $sql = 'INSERT INTO ' . $connection->quoteTableName($table)
                . ' (' . implode(', ', $names) . ') VALUES ('
                . implode(', ', $placeholders) . ')';
            } else {
                $sql .= ',(' . implode(', ', $placeholders) . ')';
            }
            $i++;
        }
        $command = Yii::app()->db->createCommand($sql);
        return $command->execute($params);
    }
}

随处使用:

$rows = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Mark')
);
GeneralRepository::insertSeveral(User::model()->tableName(), $rows);

https://www.yiiframework.com/extension/yii-insert-multi-rows

相关问题