laravel - 通过关系软删除

标签 laravel laravel-5

我正在尝试理解一些事情。

我有一个项目模型。
一个项目可以有多个文档。
一个Document有很多DocumentData。

所以这很简单,我的模型是这样设置的

class Project extends Model
{
    protected $table = 'projects';
    protected $guarded = [];
    use SoftDeletes;

    public function document()
    {
        return $this->hasMany('App\document', 'projectId');
    }

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

        static::deleted(function($document)
        {
            $document->delete();
        });
    }
}

class Document extends Model
{
    use SoftDeletes;

    protected $table = 'document';
    protected $guarded = [];

    public function project()
    {
        return $this->belongsTo('App\Project', 'projectId');
    }

    public function documentData()
    {
        return $this->hasMany('App\DocumentData', 'documentId');
    }

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

        static::deleted(function($document)
        {
            $document->documentData()->delete();
        });
    }
}

class DocumentData extends Model
{
    use SoftDeletes;

    protected $table = 'document_data';
    protected $guarded = [];

    public function document()
    {
        return $this->belongsTo('App\Document', 'documentId');
    }
}

我想了解启动功能以及我是否已正确设置它?当我删除项目时,会设置其deleted_at 时间戳。我还在寻找它来设置所有项目文档和文档数据的删除时间戳。

目前,当我删除项目时,会设置其deleted_at时间戳。 Document 和 DocumentData 保持为空。

如何实现所有相关模型的软删除?

谢谢

最佳答案

您正确使用了boot方法。我唯一注意到的是 Project 的已删除事件的处理程序中存在错误。您在删除该实例后尝试再次删除该实例。相反,我想您想删除关联的文档,如下所示:

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

    static::deleted(function($project)
    {
        $project->document()->delete();
    });
}

替代方法:

我通常删除子项的方法是重写父模型上的 delete() 方法。我更喜欢这种方式生成的代码,但这只是个人喜好。

在你的情况下,这将是:

class Project extends Model {
    public function delete()
    {
        parent::delete();  // first delete the Project instance itself
        $this->document()->delete();  // delete children
    }
}

class Document extends Model {
    public function delete()
    {
        parent::delete();
        $this->documentData()->delete();
    }
}

关于laravel - 通过关系软删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37272292/

相关文章:

php - 如何在 Laravel 5.4 中创建带有彩色 <option> 元素的下拉列表?

laravel - 将 gulp 与 Laravel Elixir 一起使用 - 禁用托盘图标消息?

javascript - 从 ajax 获取参数到 Controller Laravel

php - Laravel Socialite 扩展领域

php - 错误 "Trying to access array offset on value of type null"laravel 5.8.26 Php 7.4.2

php - Laravel 5.4 迁移 ENUM 在 MySQL 中失败

php - 找不到 Laravel 5 View

php - 错误 : 1215 Cannot add foreign key constraint 的问题

javascript - 单击滚动到 Laravel/Blade 中的下一个 div 类

javascript - $(selector).each 在 Laravel 的表行上