警予:保存多个记录在一个查询(Yii: save multiple records in one q

2019-10-19 06:44发布

我试图节省了大量的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);

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

Answer 1:

你可以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
}


Answer 2:

对于插入多行,把这个代码components文件夹下GeneralRepository.php文件名。

<?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



Answer 3:

由于v1.1.14,该方法createMultipleInsertCommand()CDbCommandBuilder类是可用的。



文章来源: Yii: save multiple records in one query