【问题标题】:Nested Eloquent model events not firing in Laravel 5.2?嵌套的 Eloquent 模型事件在 Laravel 5.2 中没有触发?
【发布时间】:2016-12-31 07:54:55
【问题描述】:

我有一个使用 Laravel 5.2 构建的医疗网络应用程序,我需要在删除与患者相关的记录时删除它们。我无法使用 Eloquent 事件删除它们。

一个病人有很多属于那个病人的遭遇,而那个遭遇有很多属于那个遭遇的遭遇症状。 这是我的数据库架构:

目前,我删除所有患者“遭遇”的方法是在删除患者时删除它们,即在 eloquent 模型触发时通过侦听来删除相关遭遇:

//In App\Models\Patient\Patient.php
public function Encounters(){
    return $this->hasMany('App\Models\Patient\Encounter');
}

protected static function boot() {
    parent::boot();

    static::deleting(function($Patient) { 
         $Patient->Encounters()->delete();
    });
}

在我的 Encounter 模型中,我有这个:

    //In App\Models\Patient\Encounter.php
    public function EncounterSymptoms(){
        return $this->hasMany('App\Models\Encounter\EncounterSymptom');
    }
    protected static function boot() {
    parent::boot();

    static::deleting(function($Encounter) {
         $Encounter->EncounterSymptoms()->delete();
    });
    }

使用 tinker,我选择了 Encounter 的一个实例,然后将其删除,这确实删除了相关的 EncounterSymptom 记录,但是当我对患者调用 delete 时,所有相关的 Encounter 都已成功删除,但 EncounterSymptoms 没有。我做错了什么?

【问题讨论】:

  • 可能是 EncounterSymptoms 表的软删除问题。

标签: php laravel laravel-5.2


【解决方案1】:

如果您使用迁移,则需要设置onDelete 级联。

例如,在创建 Encounters 表时:

$table->foreign('patient_id')
      ->references('id')->on('Patients')
      ->onDelete('cascade');

同样,在 EncounterSymptom 表上:

$table->foreign('encounter_id')
      ->references('id')->on('Encounters')
      ->onDelete('cascade');

请参阅文档中的迁移 -> Foreign Key Constraints 部分。

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2017-05-08
    • 2016-09-11
    • 2023-03-22
    • 2017-02-19
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多