批量“替换为”CodeIgniter Active Record

时间:2015-09-18 06:31:53

标签: php mysql codeigniter

CodeIgniter提供了一个很棒的功能,可以批量更新名为update_batch()

http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch#CI_DB_query_builder::update_batch

它还提供了一个函数replace()来执行replace into mysql查询

http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=replace#CI_DB_query_builder::replace

有没有办法获得replace_batch()或同等的东西?我正在使用一个带有替换内部的循环,但是想象一个函数会更好

1 个答案:

答案 0 :(得分:2)

如果你想克隆my repository,我已经实施了。 I tried让解决方案进入主分支,但似乎narfbg坚决反对它。也许社区的更多参与可以实现它。

/**
 * Replace_Batch
 *
 * Compiles batch insert strings replacing any existing rows and runs the queries
 *
 * @param   string  $table  Table to replace insert into
 * @param   array   $set    An associative array of insert values
 * @param   bool    $escape Whether to escape values and identifiers
 * @return  int Number of rows inserted or FALSE on failure
 */
public function replace_batch($table, $set = NULL, $escape = NULL, $batch_size = 100)
{
    if ($set === NULL)
    {
        if (empty($this->qb_set))
        {
            return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
        }
    }
    else
    {
        if (empty($set))
        {
            return ($this->db_debug) ? $this->display_error('replace_batch() called with no data') : FALSE;
        }

        $this->set_insert_batch($set, '', $escape);
    }

    if (strlen($table) === 0)
    {
        if ( ! isset($this->qb_from[0]))
        {
            return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
        }

        $table = $this->qb_from[0];
    }

    // Batch this baby
    $affected_rows = 0;
    for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size)
    {
        if ($this->query($this->_replace_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size))))
        {
            $affected_rows += $this->affected_rows();
        }
    }

    $this->_reset_write();
    return $affected_rows;
}

// --------------------------------------------------------------------

/**
 * Replace batch statement
 *
 * Generates a platform-specific insert string from the supplied data.
 *
 * @param   string  $table  Table name
 * @param   array   $keys   INSERT keys
 * @param   array   $values INSERT values
 * @return  string
 */
protected function _replace_batch($table, $keys, $values)
{
    return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
}

上面的代码与Github完全相同,因此解决方案可以转发回stackoverflow.com。但遗憾的是我对stackoverflow的回复限制为30k字符,因此我无法粘贴整个提交,其中还包括对db驱动程序的更改。