我目前用laravel,數(shù)據(jù)庫查詢出來是對象,每次還得轉(zhuǎn)成數(shù)組, 而且沒有批量更新功能
laravel有同時自增自減的Db::功能嗎?
//+1
Db::table('options')->where('id', $option_id)->increment('num', 1);
//-1
Db::table('options')->where('id', $option_id)->decrement('user_num', 1);
這種得寫兩次, 想一次性更新自增和自減
laravel ORM好還是TP ORM好呢? 從查詢效率上來比較
public function updateBatch($tableName, $multipleData = [])
{
try {
if (empty($multipleData)) {
throw new \Exception("數(shù)據(jù)不能為空");
}
$firstRow = current($multipleData);
$updateColumn = array_keys($firstRow);
// 默認(rèn)以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 . ")";
// 傳入預(yù)處理sql語句和對應(yīng)綁定數(shù)據(jù)
return Db::update($updateSql, $bindings);
} catch (\Exception $e) {
return false;
}
}