我有一个具有状态(字符串)和当前任务(任务模型的外键)的样例模型.
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();
}
}
我希望在更新样本时触发此操作,判断是否有关联的任务,如果有,则将状态更改为正在进行中.
我遇到了两个问题:
- 当手动更新当前任务id字段并运行save()时,我得到了由观察器代码以某种方式引起的内存泄漏.
- 当运行"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()会导致内存泄漏?