【问题标题】:Laravel - Customize model eventLaravel - 自定义模型事件
【发布时间】:2021-10-29 08:17:55
【问题描述】:

所以我的 Comment 模型有以下模型事件:

public static function boot()
{
    parent::boot();

    self::created(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

    self::updated(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

    self::deleted(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

但是,有什么方法可以让我稍微自定义一下吗?所以假设我希望更新模型事件在它更新时触发,但如果它以某种方式更新(比如更新特定列),它可以传递一个特殊参数。

类似这样的:

    self::updated(function ($model) {
       if (//// "text" column update)
        $model->clearCache(1);
       } else {
        $model->clearCache(0);
       }
    });

【问题讨论】:

    标签: laravel


    【解决方案1】:

    https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Concerns/HasAttributes.html#method_getDirty

    getDirty() :获取自上次同步以来已更改的属性。

    self::updated(function ($model) {
       $columns = $model->getDirty();
    
       foreach ($columns as $column => $newValue) {
         echo $column; // One of the changed columns.
         if ($column == 'YOUR_COLUMN_NAME')
            $model->clearCache(1);
         } else {
            $model->clearCache(0);
       }
    }
    });
    

    【讨论】:

    • 我不太喜欢这个解决方案,因为它会在每次模型更新时添加一个数据库查询。
    【解决方案2】:

    我想出的解决办法就是悄悄地更新模型,然后在传递我想要的参数的同时调用我想要的函数:

    $comment->saveQuietly();
            
    $comment->clearCache($parameter);
    

    【讨论】:

      猜你喜欢
      • 2017-02-04
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多