Ad

Model Inheritance In OctoberCMS/Laravel (composite Pattern)

- 1 answer

So, we're developing a web app based on OctoberCMS, and we have the following requirement: There are macro sections, sections, and subsections. Each subsection belong to a section, and each section belong to a macro section. Subsections don't always exists though.

Also, there are products, and each product has a category, and that category may belong to a subsection, section or macro section.

In something like Django, for example, I would implement something like the composite pattern, I'd have a base section model (BaseSection), and 3 children of that class, MacroSection, Section, and Subsection.

Then I could either: set, in BaseSection, a nullable "parent" field, that's a foreign key to BaseSection itself; or have different fields for each children, to limit the structure (MacroSection wouldn't have any, section would have a MacroSection parent field, and subsection a Section parent field).

Finally I would have a BaseSection field in the product category model (since the category can belong anywhere in the hierarchy).

But I'm not sure what's the best way to implement this here.

The best I have is this: Create only one "base_section" table with an additional field saying what kind of section it is. Something like this:

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');
});

And then I use October models to define all the section classes:

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

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

//Other classes

I'm missing some hierarchy restrictions but I can work on them later.

Does this make sense? Is there a better solution?

Thanks.

Ad

Answer

What you suggest should work, but also look into polymorphic relations, that may suit your model, not sure:

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

Ad
source: stackoverflow.com
Ad