2017-05-17 10 views
1

ここでは、モデルの2つのイベントを扱っています。以下のコードでは更新と更新を行っています。私の懸念は、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"); 
} 

} 

これは正しいですか?もし私が間違っているのであれば?

答えて

1

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'); 
} 
+0

クール、私はそれを試してみましょう:) – BlackBurn027

+0

それは私にとって完璧にうまくいくようです – BlackBurn027

関連する問題