然后里边放置下面内容
<?php namespace App\Observers; use Log; use App\Models\GoodsCategory; class GoodsCategoryObserver { public function creating(GoodsCategory $goodsCategory) { //如果创建的是一个根类目 if (is_null($goodsCategory->parent_id)) { //讲层级设置为0 $goodsCategory->level = 0; //将path 设为 - $goodsCategory->possess = '-'; }else { //将层级设为父类目层级 + 1 $goodsCategory->level = $goodsCategory->parent->level +1; Log::info($goodsCategory->level); // 将path 设为父级目的的PATH 追加父级的id 并最后 跟上一个 - 分隔符 $goodsCategory->possess = $goodsCategory->parent->possess.$goodsCategory->parent_id.'-'; } } /** * Handle the goods category "created" event. * * @param \App\GoodsCategory $goodsCategory * @return void */ public function created(GoodsCategory $goodsCategory) { } /** * Handle the goods category "updated" event. * * @param \App\GoodsCategory $goodsCategory * @return void */ public function updated(GoodsCategory $goodsCategory) { // } /** * Handle the goods category "deleted" event. * * @param \App\GoodsCategory $goodsCategory * @return void */ public function deleted(GoodsCategory $goodsCategory) { // } /** * Handle the goods category "restored" event. * * @param \App\GoodsCategory $goodsCategory * @return void */ public function restored(GoodsCategory $goodsCategory) { // } /** * Handle the goods category "force deleted" event. * * @param \App\GoodsCategory $goodsCategory * @return void */ public function forceDeleted(GoodsCategory $goodsCategory) { // } }
然后需要注册一个服务
app\Providers\ModelObserverProvider.php
php artisan make:provider ModelObserverProvider
里边添加这些代码
<?php namespace App\Providers; use App\Observers\GoodsCategoryObserver; use App\Models\GoodsCategory; use Illuminate\Support\ServiceProvider; class ModelObserverProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { // } /** * Bootstrap services. * * @return void */ public function boot() { GoodsCategory::observe(GoodsCategoryObserver::class); } }