💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
给模型绑定了观察器,注册了deleted事件,预计以下代码会被触发 ~~~ User::where('id', 1)->delete(); ~~~ 然而理想是美好的,现实是残酷的,仔细检查了流程, 感觉Perfect,最终几经波折找到如下攻略 ![](https://box.kancloud.cn/74a0af1062093eb75df898377c780763_1468x898.png) 总结如下 敲黑板! 检索了模型实例的的操作才会被触发 ~~~ // 这样是不行的 User::where('id', 1)->delete(); // 这样是可行的 $user = User::find(1); $user->delete(); // 或者 User::destroy(1); User::destroy([1, 2]); ~~~ ~~~ $user = User::find(1); $user->delete(); ~~~ 这个是调用 \Illuminate\Database\Eloquent\Model:delete() 方法,源码里写了会在 delete 前后触发 deleting 和 deleted 事件,源码是: ~~~ public function delete() { if (is_null($this->getKeyName())) { throw new Exception('No primary key defined on model.'); } // If the model doesn't exist, there is nothing to delete so we'll just return // immediately and not do anything else. Otherwise, we will continue with a // deletion process on the model, firing the proper events, and so forth. if (! $this->exists) { return; } if ($this->fireModelEvent('deleting') === false) { return false; } // Here, we'll touch the owning models, verifying these timestamps get updated // for the models. This will allow any caching to get broken on the parents // by the timestamp. Then we will go ahead and delete the model instance. $this->touchOwners(); $this->performDeleteOnModel(); // Once the model has been deleted, we will fire off the deleted event so that // the developers may hook into post-delete operations. We will then return // a boolean true as the delete is presumably successful on the database. $this->fireModelEvent('deleted', false); return true; } ~~~ 而 ~~~ User::where('id', 1)->delete(); ~~~ 调用的是 Illuminate\Database\Eloquent\Builder::delete(),然后调用 Illuminate\Database\Query\Builder::delete() ,源码里没有加上事件,直接删除数据了,Illuminate\Database\Query\Builder::delete() 源码是: ~~~ public function delete($id = null) { // If an ID is passed to the method, we will set the where clause to check the // ID to let developers to simply and quickly remove a single row from this // database without manually specifying the "where" clauses on the query. if (! is_null($id)) { $this->where($this->from.'.id', '=', $id); } return $this->connection->delete( $this->grammar->compileDelete($this), $this->cleanBindings( $this->grammar->prepareBindingsForDelete($this->bindings) ) ); } ~~~