increment 和 decrement 添加条件使用的疑惑
问题:当不加等于条件并且加其他条件时,更新了所有行数。为何没有自动加上主键等于判断呢?
//按照条件查询出一条数据 并且调用方法
$coupon = CouponCode::where('code', 'bviytx3qbq58gxcx')->first();
$json = $coupon->changeUsed();
return response()->json($json);
public function changeUsed($increase = true) {
DB::enableQueryLog();
if ($increase) {
//注意这里加上了一个不是等于的条件更新
$this->where('used','<', $this->total)->increment('used');
}
//此处不加任何条件
$this->decrement('used');
return DB::getQueryLog();
}
//increment和decrement调用的源码
protected function incrementOrDecrement($column, $amount, $extra, $method)\
{\
$query = $this->newQueryWithoutRelationships();\
\
if (! $this->exists) {\
return $query->{$method}($column, $amount, $extra);\
}\
\
$this->incrementOrDecrementAttributeValue($column, $amount, $extra, $method);\
\
return $query->where(\
$this->getKeyName(), $this->getKey()\
)->{$method}($column, $amount, $extra);\
}
打印出的执行语句
经过测试,确实会出现主键丢失的情况,好像是因为 where 构建一个新的 Model,打印了一下源码中的 $this->getKeyName(), $this->getKey(),都不存在了。
可能模型的初衷不是这样使用的,可以这样实现