【问题标题】:eloquent events, can I use them in model class?雄辩的事件,我可以在模型类中使用它们吗?
【发布时间】:2017-02-01 06:20:25
【问题描述】:

我正在阅读 laravel softdelete 并在此处恢复级联:Laravel 5: cascade soft delete

用户所说的:

You should use Eloquent events for this.

Offers::deleted(function($offer) {
    $offer->services()->delete();
});
Offers::restored(function($offer) {
    $offer->services()->withTrashed()->restore();
});

他没有提到将这段代码放在哪里,我有兴趣倾听雄辩的删除和恢复事件。我可以把这段代码放在哪里?我可以在模型课上听吗?如果不是放在哪里?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我觉得……

    <?php
    class Attribute extends Model implements Transformable
    {
    //....
    protected static function boot() {
        parent::boot();
    
        static::deleting(function($model) {
            foreach ($model->attributeValue()->get() as $attributeValue) {
                $attributeValue->delete();
            }
        });
    
    }
    

    或者例子:

    class BaseModel extends Model
    {
        public static function boot()
        {
            static::creating(function ($model) {
            // blah blah
            });
    
            static::updating(function ($model) {
            // bleh bleh
            });
    
            static::deleting(function ($model) {
            // bluh bluh
            });
    
           parent::boot();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 1970-01-01
      • 2020-10-02
      • 2021-08-11
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多