laravel5批量更新函数

updateBatch

主要用于批量更新不同id的不同属性
自带的update仅支持更新相同属性内容
例如:文章列表的排序更新

第二个参数为表名
配合model方法Article::getabname()

public static function getabname()
{
        return env('DB_PRE').with(new static)->getTable();
}
/*
 * ----------------------------------
 * update batch 
 * ----------------------------------
 * multiple update in one query
 *
 * multipleData ( required | array of array )
 * tablename( required | string )
 */
function updateBatch($multipleData = array(), $tableName = "articles"){

    if( $tableName && !empty($multipleData) ) {
        // column or fields to update
        $updateColumn = array_keys($multipleData[0]);
        $referenceColumn = $updateColumn[0]; //e.g id
        unset($updateColumn[0]);
        $whereIn = "";

        $q = "UPDATE `".$tableName."` SET `"; 
        foreach ( $updateColumn as $uColumn ) {
            $q .=  $uColumn."` = CASE ";

            foreach( $multipleData as $data ) {
                $q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";
            }
            $q .= "ELSE `".$uColumn."` END, ";
        }
        foreach( $multipleData as $data ) {
            $whereIn .= "'".$data[$referenceColumn]."', ";
        }
        $q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (".  rtrim($whereIn, ', ').")";

        // Update  
        return \DB::update(DB::raw($q));

    } else {
        return false;
    }
}

使用方法

    $ids = $request->id;
    if(!count($ids))
    return redirect()->back()->withErorr('没有需要更新的数据!');
    $orders = $request->order;
    foreach ($ids as $key => $value) {
        $update[]=['id'=>$value,'order'=>$orders[$key]];
    }
    $ok = updateBatch($update,Article::getabname());
    if($ok){
        return redirect()->back()->withMessage('移动成功!');
    }else{
        return redirect()->back()->withErorr('更新失败!');
    }

你可能感兴趣的:(laravel5批量更新函数)