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);\
}

打印出的执行语句
increment 和decrement 添加条件使用的疑惑

桃知夭夭
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

经过测试,确实会出现主键丢失的情况,好像是因为 where 构建一个新的 Model,打印了一下源码中的 $this->getKeyName(), $this->getKey(),都不存在了。
可能模型的初衷不是这样使用的,可以这样实现

if ($increase && $this->used < $this->total) {
    $this->increment('used');
}
4年前 评论
讨论数量: 2

经过测试,确实会出现主键丢失的情况,好像是因为 where 构建一个新的 Model,打印了一下源码中的 $this->getKeyName(), $this->getKey(),都不存在了。
可能模型的初衷不是这样使用的,可以这样实现

if ($increase && $this->used < $this->total) {
    $this->increment('used');
}
4年前 评论

@畅畅 我的直觉告诉我这个是个BUG,哈哈。你的这个方式可以,多谢~

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!