我有一个具有状态(字符串)和当前任务(任务模型的外键)的样例模型.

field              type
---------------------------
id                 int
status             string -> I use an Enum to store possible values
current_task_id    int -> foreign key to the Task model

在我的模型中,我将这种关系定义为:

public function currentTask()
{
    return $this->belongsTo(Task::class, 'current_task_id', 'id');
}

现在,我已经创建了一个具有以下函数的观察者:

public function updated(Sample $sample)
{
    // check if the current task is null and if not change the status to in progress
    Log::info('Sample status changed to in progress', ['sample' => $sample->toArray()]);
    if ($sample->currentTask()->exists()) {
        $sample->status = 'in progress';
        $sample->save();
    }
}

我希望在更新样本时触发此操作,判断是否有关联的任务,如果有,则将状态更改为正在进行中.

我遇到了两个问题:

  1. 当手动更新当前任务id字段并运行save()时,我得到了由观察器代码以某种方式引起的内存泄漏.
  2. 当运行"Associate"方法来分配currentTask时,观察者不会触发.

请参见下面我在Tinkerwell中运行的代码

$sample = Sample::factory()->create();
echo $sample->currentTask(); // null
echo $sample->status;        // not started
$sample->current_task_id = 2;
$sample->save();             // memory leak, additionally, if I check $sample->currentTask it gives me null...

或与联营公司:

$sample = Sample::factory()->create();
echo $sample->currentTask(); // null
echo $sample->status;        // not started
$sample->currentTask()->associate(2); // does not trigger observer
echo $sample->currentTask(); // Task object
echo $sample->status;        // not started

我如何在助理上触发观察者?或者,为什么SAVE()会导致内存泄漏?

推荐答案

以下是我的建议:

继续使用观察者,但使用保存(或更新)方法:

public function saving(Sample $sample)
{
    // check if the current task changed
    Log::info('Sample status changed to in progress', ['sample' => $sample->toArray()]);
    if ($sample->isDirty('current_task_id') && CurentTask::where('id', $sample->current_task_id)->exists()) {
        $sample->status = 'in progress';
    }
}

如果您在savingupdating事件中不使用isDirty判断,您将结束保存的无限循环,触发updated,然后再次保存

Php相关问答推荐

CodeIgniter AJAX表格提交中的CSRF token 再生问题

从WooCommerce邮箱通知中的订单详细信息中删除产品列表

累加平面数组中数字子集的所有组合,以生成组合及其乘积的二维数组

如何使用`preg_replace`删除重复的空格字符

以编程方式更改新订单、已取消订单和失败订单的邮箱WooCommerce通知

有没有可能从composer 过时的输出中隐藏不需要的主要版本?

在laravel 9或10 php中向中间件响应添加自定义数据

设置WordPress最近的帖子小部件按修改日期排序

在WP工具中页面加载时可短暂看到的JavaScript生成的字段

Azure应用程序无法访问共享文件夹

如何解决 Laravel 外键错误?

如何使用 AJAX、PHP 和 MYSQL 在 Select 项目时在文本框中填充数据

WooCommerce:如果订单总数为零,则隐藏本地取货运输选项

如何在 PHP laravel 中将图像的透明背景转换为白色?

WordPress 分页无法正常工作

正则表达式将文本替换为标签 html 以字符开头

PHP 创建 CSV 文件并用波斯语写入

CodeIgniter 4中嵌套过滤器组不起作用

Woocommerce注册中的自定义复选框验证错误提示问题

如何将 2021-04-08T22:25:09.335541Z 作为时间戳保存到 Laravel 中的数据库中?