我正在尝试理解一些事情。
我有一个项目模型。
一个项目可以有多个文档。
一个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/