gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:27:37 25 4
gpt4 key购买 nike

我在这里处理模型的两个事件,更新和更新,如下面的代码所示。我担心的是,只有在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");
}

}

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

最佳答案

在 Eloquent 模型中,您可以使用 getOriginal更新属性时的方法。
所以如果你想得到teacherId的原始值(更新前)你可以做:

$subject->getOriginal('teacher_id');
https://laravel.com/api/5.5/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');
}

关于laravel - 仅在更新模型属性/列时处理事件 - Laravel Observer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44024910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com