批量更新和插入mysql數據庫

項目需要通過腳本批量插入和更新數據

傳統的循環單條插入和更新非常影響性能,故需要批量插入(1條SQL批量插入)和批量更新(1條SQL批量更新)

    /**
     * 批量賦值
     * @param array $data
     * @return bool
     */
    public static function batchInsert(Array $data)
    {
        $table = with(new static())->getTable();
        $rs = DB::table($table)->insert($data);
        return $rs;
    }
 /**
     * 批量更新
     * @param $multipleData
     * @return bool
     */
    public static function batchUpdate($multipleData)
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("數據不能爲空");
            }
            $tableName = DB::getTablePrefix() . with(new static())->getTable(); // 表名
            $firstRow = current($multipleData);

            $updateColumn = array_keys($firstRow);
            // 默認以id爲條件更新,如果沒有ID則以第一個字段爲條件
            $referenceColumn = isset($firstRow['id']) ? 'id' : cur
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章