我目前用laravel,数据库查询出来是对象,每次还得转成数组, 而且没有批量更新功能
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("数据不能为空");
}
$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;
}
}
看你使用习惯啦
熟悉哪个用哪个
哪个都行,没什么鸟区别
你说的不是ORM,那只是查询结构器
一看就没有看文档
怎么可能没有批量更新
哪里?
https://learnku.com/docs/laravel/9.x/eloquent/12251#32ac15