【问题标题】:Force trigger of updating + updated events强制触发更新+更新事件
【发布时间】:2014-06-09 02:54:44
【问题描述】:

我注意到如果模型中没有更改,模型将不会调用更新或更新事件。我猜它会将getOriginalgetDirty 进行比较。

但是,当我只更新模型的关系时,例如,附加新类别,因为此操作存在于更新的事件中,它永远不会被触发。

在这种特定情况下,更新事件期间会删除类别,而更新事件期间会附加新类别。但只有在我更改模型中的至少一个值时才会触发它。

我错过了什么吗?

这在 4.1 中没有发生,现在在 4.2 中发生了,作曲家今天更新了。

更新:

这是我的 Product 模型启动时的 updatingupdated 事件:

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

    static::updating(function($model)
    {
        $model->author_id = 1;//Auth::user()->id;

        $history = new ProductHistory($model->getOriginal());            
        $model->history()->save($history);

        $model->languages()->update(array(Product::$historyKey => $history->id));
        $model->currencies()->update(array(Product::$historyKey => $history->id));
        $model->paymentTypes()->update(array(Product::$historyKey => $history->id));
    }

    static::updated(function($model)
    {
        if(Input::has('languages')) $model->languages()->attach(Input::get('languages'));
        if(Input::has('currencies')) $model->currencies()->attach(Input::get('currencies'));
        if(Input::has('payment_types')) $model->paymentTypes()->attach(Input::get('payment_types'));
    }
}

还有BaseModel中的updating事件:

    static::updating(function($model)
    {
        if(property_exists(get_class($model), 'rules'))
        {               
           if(!$model->validate()) return false;
        }
    });

这在 4.2 中不再起作用,因为当模型没有更改时,更新和更新事件将被忽略。我的修复是只使用savingsaved 事件,在这些事件中,我可以通过检查getOriginal()是否存在来确定模型是否正在更新或创建。

【问题讨论】:

  • 保存负责更新的代码。
  • @WereWolf-TheAlpha 您好,狼人先生,我已经更新了问题。

标签: php laravel eloquent


【解决方案1】:

触发父模型的update 的最简单方法是在子模型中添加$touches 属性,例如,如果您要更新作为另一个模型的子模型的ProductHistory 模型,则只需添加以下ProductHistory 模型中的属性:

// Add this in ProductHistory model
protected $touches = array('Product');

现在,每次更新 ProductHistory 时,它也会更新其父模型中的 updated_at 字段,在本例中为 Product 模型,因此 updated_at 字段将被更新,并且更新事件也会触发并且在更新子模型时更新父模型的updated_at 属性是有意义的。

Laravel 网站中查看Touching Parent Timestamps

【讨论】:

  • 这看起来不错,先生,但在这种情况下 ProductHistory 正在更新事件中创建。 getOriginal() 不应该返回模型的关系吗?
猜你喜欢
  • 2019-11-15
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2019-02-27
  • 2020-07-15
  • 2013-11-22
相关资源
最近更新 更多