Codeigniter - Batch Update with Multiple Where Conditions

前端 未结 3 644
无人及你
无人及你 2020-12-11 01:30

For starters, the Codeigniter documentation on update_batch does not exist. kenjis was kind enough to provide some documentation and submit it to the repository. Hopefully t

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 01:49

    Multiple where conditions are broken in update_batch because the WHERE query is being cleared in the batch loop.

    Here is the batch update loop:

            for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size)
            {
                if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index)))
                {
                    $affected_rows += $this->affected_rows();
                }
    
                $this->qb_where = array();
            }
    

    Notice that the passed WHERE conditions are cleared by $this->qb_where = array();.

    In CodeIgniter v3.1.10, the offending line is on 1940 in DB_query_builder.php. This produces a very unexpected behavior where WHERE conditions work for the first batch processed (default 100) and fail for subsequent batches.

    There are two possible solutions:

    1. Use the 4th batch_size parameter of update_batch and pass a large number such as 100,000 so all the queries are processed in the first batch and the WHERE condition is not cleared.
    2. Update the offending line to restore the initial WHERE conditions.

    Code for Solution #2:

            // Save initial where conditions.
            $where_holder = $this->qb_where;
            // Batch this baby
            $affected_rows = 0;
            for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size)
            {
                if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index)))
                {
                    $affected_rows += $this->affected_rows();
                }
    
                // Restore intial where conditions.
                $this->qb_where = $where_holder;
            }
    

    Hope this helped!

提交回复
热议问题