【问题标题】:Laravel deleted event on mass delete for loggingLaravel 在批量删除时删除事件以进行日志记录
【发布时间】:2022-08-14 15:22:51
【问题描述】:

我正在尝试将 spatie 活动日志用于可以正常创建和更新事件的模型,但不适用于已删除的事件。

经过一番谷歌搜索,我得到了以下信息

When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

是否有任何解决方法可以在调度事件时批量删除所选项目,以便 ActivityLog 可以将其拾取?除了通过循环遍历所选项目并删除它们或循环遍历它们并为每个手动添加日志活动来手动执行此操作。

// Delete all selected units that are not in the parentsIds array
    Unit::whereIn(\'id\',$this->selected)->whereNotIn(\'id\',$this->parentsIds)->delete();

这就是模型

// Activity Logging
protected static $recordEvents = [\'deleted\', \'updated\', \'created\'];
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
    ->logOnly([\'name\', \'type\',\'Parent.name\']);
    // Chain fluent methods for configuration options
}
  • 对于要触发的模型事件delete 必须在模型实例上调用,直接删除查询不会这样做......您甚至无法知道执行删除时实际删除了哪些记录询问

标签: laravel eloquent


【解决方案1】:

您可以检索模型实例

$unitsToDelete = Unit::whereIn('id',$this->selected)->whereNotIn('id',$this->parentsIds)

然后对每条记录使用循环调用删除方法

foreach($unitsToDelete as $unit) {Unit::find($unit->id)->delete()}

不是更好和优雅的方式,而是解决问题的解决方法

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多