【问题标题】:Model inheritance in OctoberCMS/Laravel (composite pattern)OctoberCMS/Laravel 中的模型继承(复合模式)
【发布时间】:2020-09-08 21:14:05
【问题描述】:

所以,我们正在开发一个基于 OctoberCMS 的网络应用,我们有以下要求:有宏部分、部分和子部分。每个小节属于一个节,每个节属于一个宏节。不过,小节并不总是存在。

此外,还有产品,每个产品都有一个类别,该类别可能属于一个小节、节或宏节。

例如,在 Django 之类的东西中,我将实现类似复合模式的东西,我将有一个基本部分模型 (BaseSection),以及该类的 3 个子类:MacroSection、Section 和 Subsection。

然后我可以:在 BaseSection 中设置一个可为空的“父”字段,它是 BaseSection 本身的外键;或为每个子项设置不同的字段,以限制结构(MacroSection 没有任何字段,section 将有一个 MacroSection 父字段,而 subsection 有一个 Section 父字段)。

最后,我将在产品类别模型中有一个 BaseSection 字段(因为该类别可以属于层次结构中的任何位置)。

但我不确定在此处实现此功能的最佳方法是什么。

我拥有的最好的是:只创建一个“base_section”表,其中包含一个额外的字段,说明它是什么类型的部分。像这样的:

Schema::create('base_section', function($table) {
    //other fields

    $table->foreign('parent_section')->references('id')->on('base_section')->nullable();
    //Does that even work here by the way? Or do I have to make another instruction after the create?
    
    $table->string('section_type');
});

然后我使用十月模型来定义所有的部分类:

class BaseSection extends Model {
    protected $table = 'base_section';
}

class Subsection extends BaseSection {
    public function beforeCreate() {
        $this->section_type = 'subsection';
    }           
}

//Other classes

我缺少一些层次结构限制,但我可以稍后处理它们。

这有意义吗?有没有更好的解决方案?

谢谢。

【问题讨论】:

    标签: php laravel octobercms


    【解决方案1】:

    你的建议应该可行,但也要研究多态关系,可能适合你的模型,不确定:

    https://octobercms.com/docs/database/relations#polymorphic-relations

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 2014-07-21
      • 2018-06-16
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2013-12-24
      • 2012-02-17
      • 2017-06-12
      相关资源
      最近更新 更多