仅在更新模型属性/列时处理事件 - Laravel Observer

问题描述 投票:2回答:1

我在这里处理模型的两个事件,更新和更新,如下面的代码所示。我担心的是,只有当teacherId被更改时,我才想在更新的事件中执行一些任务。所以我想在更新事件中检查值并使用类属性来知道它是否已被更改但是该标志假定其定义的值,则始终返回false。

namespace App\Observers;

class SubjectObserver {

private $shouldUpdateThreads = false;

/**
 * Listen to the ThreadList created event.
 * This events Fire when ThreadList is handled
 * @param \App\Observers\App\ThreadList $threadList
 */
public function created(\subject $subject) {

}

/**
 * Listen to the ThreadList saved event.
 * @param \App\Observers\App\ThreadList $threadList
 */
public function saved(\subject $subject) {

}

/**
 * Handling subject updated event 
 * Used to update the threads and related models
 * @param \subject $subject
 */
public function updated(\subject $subject) {
    info('After Update Event ' . $this->shouldUpdateThreads);
    if ($this->shouldUpdateThreads) {
        info_plus($subject);
    }
    info('After Update Check');
}

/**
 * Handling subject being updated event
 * Used to check if the teachers data has changed or not
 * @param \subject $subject
 */
public function updating(\subject $_subject) {

    $subject = \subject::find($_subject->id);

    $this->shouldUpdateThreads = ($subject->teacherId != $_subject->teacherId) ? true : false;

    info(($subject->teacherId != $_subject->teacherId));

    info("Thread update ? " . $this->shouldUpdateThreads);
}

public function deleted(\subject $subject) {
    info("Subject deleted");
}

}

这甚至是正确的方法吗?如果不是我做错了什么?

laravel model eloquent observers laravel-events
1个回答
3
投票

在Eloquent Models中,您可以在更新属性时使用getOriginal方法。因此,如果您想获得teacherId的原始值(更新前),您可以:

$subject->getOriginal('teacher_id');

https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Model.html#method_getOriginal

在你的代码中:

public function updated(\subject $subject) {
    info('After Update Event ' . $this->shouldUpdateThreads);
    if ($subject->getOriginal('teacher_id') !== $subject->teacher_id) {
        info_plus($subject);
    }
    info('After Update Check');
}
© www.soinside.com 2019 - 2024. All rights reserved.