laravel 批量更新

今天实现laravel 批量更新数据,发现没有这个功能,在社区也没搜到,所以网上找了一份

核心代码

public function updateBatch($tableName,$multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            $firstRow  = current($multipleData);

            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新,如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }

使用方法

$update = array(
            array('id'=>1,'name'=>'aa','area'=>'bb'),
            array('id'=>2,'name'=>'cc','area'=>'dd'),
            array('id'=>3,'name'=>'ee','area'=>'ff')
        );
        try{
            $this->updateBatch($this->Create->getTable(),$update);
            echo 'update success';
        }catch (\Exception $e){
            echo $e->getMessage();
        }

疑问

DB::table 和 Db::table有啥区别?

1808 6 2
6个评论

yzh52521

laravel update 那是什么语句 ?

批量更新
还可以批量更新与给定条件匹配的所有模型。在此示例中,所有 active 且 destination 为 San Diego 的航班都将被标记为延迟:

Flight::where('active', 1)
      ->where('destination', 'San Diego')
      ->update(['delayed' => 1]);
咸鱼姥爷

upsert 不就可以批量更新

  • PHP甩JAVA一条街 2023-02-25

    没搜到这个 -

  • 咸鱼姥爷 2023-02-26

    upsert方法将插入不存在的记录,并用您指定的新值更新已存在的记录。该方法的第一个参数由要插入或更新的值组成。而第二个参数列出列唯一标识关联表中记录的方法。方法'的第三个也是最后一个参数是一个列数组,如果数据库中已存在匹配记录,则应更新该数组 手册中有 写法参考https://learnku.com/articles/59138

  • 软饭工程师 2023-09-13
    $cases = [
        ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'],
        ['id' => 2, 'name' => 'Alice', 'email' => 'alice@example.com'],
        ['id' => 3, 'name' => 'Bob', 'email' => 'bob@example.com'],
    ];
    
    $uniqueKey = 'id';
    
    User::upsert($cases, $uniqueKey, ['name', 'email']);

    这样就能批量更新

mosquito

哈哈,我也有个,功能更齐全点,可以用表达式、分隔

if (!function_exists('laravel_batch_update')) {
    /**
     * laravel数据库单表批量更新,适用于laravel
     * @param string $table
     * @param array $list_data
     * @param int $chunk_size
     * @return int
     * @author mosquito <zwj1206_hi@163.com> 2020-10-21
     */
    function laravel_batch_update(string $table, array $list_data, int $chunk_size = 200)
    {
        if (count($list_data) < 1) {
            throw new \Exception('更新数量不能小于1');
        }
        if ($chunk_size < 1) {
            throw new \Exception('分切数量不能小于1');
        }
        $chunk_list = array_chunk($list_data, $chunk_size);
        $count      = 0;
        foreach ($chunk_list as $list_item) {
            $first_row  = current($list_item);
            $update_col = array_keys($first_row);
            // 默认以id为条件更新,如果没有ID则以第一个字段为条件
            $reference_col = isset($first_row['id']) ? 'id' : current($update_col);
            unset($update_col[0]);
            // 拼接sql语句
            $update_sql = 'UPDATE ' . $table . ' SET ';
            $sets       = [];
            $bindings   = [];
            foreach ($update_col as $u_col) {
                $set_sql = '`' . $u_col . '` = CASE ';
                foreach ($list_item as $item) {
                    $set_sql .= 'WHEN `' . $reference_col . '` = ? THEN ';
                    $bindings[] = $item[$reference_col];
                    if ($item[$u_col] instanceof \Illuminate\Database\Query\Expression) {
                        $set_sql .= $item[$u_col]->getValue() . ' ';
                    } else {
                        $set_sql .= '? ';
                        $bindings[] = $item[$u_col];
                    }
                }
                $set_sql .= 'ELSE `' . $u_col . '` END ';
                $sets[] = $set_sql;
            }
            $update_sql .= implode(', ', $sets);
            $where_in   = collect($list_item)->pluck($reference_col)->values()->all();
            $bindings   = array_merge($bindings, $where_in);
            $where_in   = rtrim(str_repeat('?,', count($where_in)), ',');
            $update_sql = rtrim($update_sql, ', ') . ' WHERE `' . $reference_col . '` IN (' . $where_in . ')';
            //
            $count += \DB::update($update_sql, $bindings);
        }
        return $count;
    }
}
  • doit 2023-07-18

    没有tp_batch_update吗

TM

好家伙 名字起得那么飘吗😄

  • 暂无评论
dongisking

在 Laravel 中,DB::table 和 Db::table 实际上是相同的,它们都是用于创建数据库查询构建器(Database Query Builder)实例的方法。

DB::table 是 Laravel 提供的默认的数据库查询构建器门面(Facade)类方法,而 Db::table 是在 Laravel 8.x 版本中引入的全局辅助函数(Global Helper Function)。
————FROM CHATGPT

  • 暂无评论
ak47f16200

被名子忽悠进来的

  • 暂无评论

PHP甩JAVA一条街

450
积分
0
获赞数
0
粉丝数
2023-01-04 加入
🔝