我有一个Lesson
模型,包含以下字段:
lesson_id
title
start_date
end_date
以及一个具有以下字段的Content
模型:
content_id
lesson_id
contentable_id
contentable_type
order
Lesson
和Content
之间存在OneToMany关系。
此外,我还有另外两个名为Unit
的模型,它们具有以下字段:
unit_id
title
time
和Test
通过这些:
test_id
title
description
内容contentable_type
和contentable_id
属性保存与特定课程相关的单元(或测试)数据。
例如,在内容的contentable_type
字段中,只能插入App''Unit或App ''Test字符串,并且contentable_id
持有该单元或测试的ID。
(请注意,内容模型不是为了在这些表之间创建变形关系,我创建了它,因为我想为单元提供订购功能并测试课程)
现在,假设我想删除一个特定的内容和相关的单元(或测试)。
删除内容模型实例很容易,但要删除相关的单元(或测试),我必须从contentable_type
中获取合适的模型名称和它的ID,然后选择并删除它。
为此,我写了这样的文章:
public function destroy ($course_id, $lesson_id, $content_id)
{
$content = Content::findOrFail($content_id);
$modelName = $content->contentable_type;
$modelName::find($content->contentable_id)->delete();
$content->delete();
}
尽管工作正常,但我认为这并不方便。我搜索一种方法,当删除一个内容模型时,它会自动找到相关的模型并将其删除。
什么是最佳和适当的解决方案?
在这种情况下,我只做以下更改:
public function destroy ($course_id, $lesson_id, $content_id)
{
$content = Content::findOrFail($content_id);
$content->delete();
}
在内容模型中:
public static function boot()
{
static::deleting(function ($content) {
$modelName = $content->contentable_type;
$modelName::find($content->contentable_id)->delete();
});
}
这很好用。但是,做这个最好和最正确的解决方案?