douan5151 2015-08-25 17:59
浏览 158
已采纳

在Laravel上使用模型的全局事件

It's basically what I need: if any model row on my project is created, updated or removed, I need call a callback to work with this model row. I'll use that to create a changelog in other model, that will not trigger this global event to avoid looping.

I tried set it like that:

Model::creating($callback);

But it doesn't worked. Work only if I set it directly to all models that I have. It's bad because I need specific one-by-one. If I create a new one, I need specify it manually. Example:

User::creating($callback);
Company::creating($callback);
...

Any change will be logged on another model, called Log. It'll not trigger this $callback, because it'll register on table logs (managed by Log) each change in other models. Something like:

$user = new User;
$user->name = "John";
$user->age = 18;
$user->save();

$user->name = "John Doe";
$user->save();

$user->delete();
$user->restore();
$user->forceDelete();

I'll register something like:

id | object_type | object_id | event_type | object_data
..   App\User      1           created      { name: John, age: 18 }
..   App\User      1           updated      { name: John Doe }
..   App\User      1           trashed      null
..   App\User      1           restored     null
..   App\User      1           removed      null
  • 写回答

2条回答 默认 最新

  • 普通网友 2015-08-26 11:09
    关注

    All Eloquent model events have the format eloquent.event:ClassName.

    You could subscribe to the eloquent.* event. Event::listen('eloquent.*', function($model) {});

    Then you can check if the current model is a log model (in which case you'd return true straight out of it to avoid infinite recursion), otherwise, save the change to your log model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改