解决 Laravel 模型中的 increment 和 decrement 方法不触发 observers
你要做的,只是将下面的代码加到模型文件里,比如 account.php
里
<?php protected function incrementOrDecrement($column, $amount, $extra, $method) { $this->{$column} = ($method == 'increment' ? $this->{$column} + $amount : $this->{$column} - $amount); $this->fireModelEvent('saving', false); $this->{$column} = ($method == 'increment' ? $this->{$column} - $amount : $this->{$column} + $amount); $result = parent::incrementOrDecrement($column, $amount, $extra, $method); $this->fireModelEvent('saved', false); return $result; }
当然了,更好的方法是
public function increment($column, $amount = 1, array $extra = []) { $this->$column = $this->$column + $amount; $this->save(); } public function decrement($column, $amount = 1, array $extra = []) { $this->$column = $this->$column - $amount; $this->save(); } }
目前尚无回复