【问题标题】:Laravel model observer method doesn't get firedLaravel 模型观察者方法不会被解雇
【发布时间】:2021-02-13 20:44:07
【问题描述】:

在我的 Laravel (7.x) 中,如果 subscriber_devices 表的记录更新为 inactive,则如果记录的值更新为 device_inventories 表,我将尝试使用 Observers

device_inventories         |    subscriber_devices
-----------------------    |    --------------------------------
# | title    | status      |    # | device_inventory_id | status
-----------------------    |    --------------------------------
1 | device-1 | active      |    1 |                   1 | active
2 | device-2 | active      |    2 |                   2 | active

例如:
假设我将subscriber_devices 的记录id = 2 更新为status = inactive,那么device_inventories / status 的值应该更新为replacement。假设设备已损坏,需要送去更换。

AppServiceProvider.php

use App\SubscriberDevice;
use App\Observers\ObserverChangeDeviceInventoryStatusToReplacement;

class AppServiceProvider extends ServiceProvider
{
   public function boot()
   {
     SubscriberDevice::observe(ObserverChangeDeviceInventoryStatusToReplacement::class);
   }
}

App\Observers\ObserverChangeDeviceInventoryStatusToReplacement.php

use App\DeviceInventory;
use App\SubscriberDevice;

class ObserverChangeDeviceInventoryStatusToReplacement
{
   public function updated(SubscriberDevice $SubscriberDevice)
   {
      DeviceInventory::where('id', $SubscriberDevice->device_inventory_id)->update([
         'status' => 'replacement'
      ]);
   }
}

App\SubscriberDevice.php

class SubscriberDevice extends Model
{
   protected $table = 'subscriber_devices';

   public function _status($token, $reason)
   {
      self::where('token', $token)->update([
         'reason' => $reason,
         'status' => 'inactive',
      ]);
   }
}

观察者方法似乎没有被触发。我做错了什么?

【问题讨论】:

  • 可能duplicate
  • 感谢@EmptyBrain,它成功了。我将发布我的工作代码。再次感谢... :)

标签: laravel updating observers


【解决方案1】:

感谢@EmptyBrain。

App\SubscriberDevice.php

class SubscriberDevice extends Model
{
   protected $table = 'subscriber_devices';

   public function _status($token, $reason)
   {
      $self = self::where('token', $token)->first();

      $self->update([
         'reason' => $reason,
         'status' => 'inactive',
      ]);
   }
}

参考laravel Eloquent model update event is not fired

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多