php - 触发 Laravel 事件

标签 php laravel events laravel-5

这是我的场景: 我正在使用 Laravel 5.5.x。 我有两个模型,以一对多的方式链接。

class Artwork extends Model
{
   //It has timestamps
   protected $table = 'artworks';
   protected $fillable = [
        'artwork_category_id'
   ];
   public function artworkCategory()
    {
        return $this->belongsTo('App\Models\ArtworkCategory');
    }
}

class ArtworkCategory extends Model
{
    use SoftDeletes;

    protected $touches = ["artworks"];

    /**
     * @var string
     */
    protected $table = 'artwork_categories';
     protected $fillable = [
        'category_name',
        'acronym',
        'deleted_at'
    ];

    public function artworks()
    {
        return $this->hasMany('App\Models\Artwork');
    }
}

触摸工作正常,因此当我更新艺术品类别时,相关艺术品的 updated_at 字段也会更新。

但我需要在每件艺术品上收听“触摸”事件。 我试过在 AppServiceProvider 的引导方法上插入“更新的”监听器,但它没有被触发。

Artwork::updated(function ($model){
            \Log::debug("HERE I AM");
        });

我试过使用观察者,但没有成功。

class ArtworkObserver
{
    public function updated(Artwork $artwork)
    {
        dd($artwork);
    }
}

AppServiceProvider 中的启动方法:

Artwork::observe(ArtworkObserver::class)

问题: 有人可以告诉我正确的方法吗?或者告诉我我哪里错了? 我不够好,无法找到可以帮助我如何做到这一点的示例。

更新 我需要实现这一点,因为我必须“解雇”Scout 以在 Artwork 索引上保存 Elasticsearch 上的更新数据。

最佳答案

$touches 很可能使用批量更新,如果您检查 Events Eloquent 部分,您会发现以下内容:

When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.


我能想到的最好的办法是,当 ArtworkCategory 更新时,您手动更新 Artwork(而不是 $touches) :

class ArtworkCategory extends Model
{
    use SoftDeletes;

     protected $fillable = [
        'category_name',
        'acronym',
        'deleted_at'
    ];

    public function artworks()
    {
        return $this->hasMany('App\Models\Artwork');
    }

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

       static::updated(function($artworkCategory)
       {
            $artworkCategory->artworks->each(function($artwork) {
                $artwork->setUpdatedAt($artwork->freshTimestamp());
                $artwork->save(); /// Will trigger updated on the artwork model
            });
       });       
   }    
}

关于php - 触发 Laravel 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476084/

相关文章:

php - 显示旧响应的 Jquery ajax 请求

拉拉维尔 : php artisan suddenly stop working

android - otto eventbus for android 在发布版本中表现不同

c# - 在 C# 中将事件从一个窗体传播到另一个窗体

javascript - 将多层 PHP 数组转换为 Javascript 对象表示法

javascript - 如何自定义 twitter iframe 滚动条的样式?

javascript - Laravel 和 Ajax : Send specific url to get data?

c++ - 另一种检查 std::queue 事件的方法?

php - 为什么我不应该在 PHP 中使用 mysql_* 函数?

php - 使用 Laravel 和希伯来语进行 URL 编码