phppluginsbuilderoctobercms

Sorting product Sort by category | WinterCMS/ OctoberCMS Plugin Builder


Another question from a noob.
On the page, I need to get a list of Categories with Subcategories something like:

I have two models - Category and Subcategory.

I'm added relationship Subcategory Model:

use \Winter\Storm\Database\Traits\SimpleTree;
public $belongsTo = [
        'category' => [
            'AName\PName\Models\Category',
            'key' => 'category_id']
    ];

Catalog Components:

$this->page['categories'] = Category::get();
$subcategories = $this->page['subcategories'] = Subcategory::where('category_id', $category->$id)->get();

I receive 'Undefined variable: category'
Where is the mistake?
Thanks in advance.


Solution

  • You can use this approach.

    You need to define sub_categories relation in to your parent model Category

    // Category Model
    public $hasMany = [
        'sub_categories' => AName\PName\Models\Subcategory
    ]
    

    Now once you get the main categories you can retrieve its sub-category by just calling sub_categories relation

    In code section

    $this->page['categories'] = Category::get();
    

    In markup section

    {% for category in categories %}
        - {{ category.title }}
        {% for subCategory in category.sub_categories %}
            -- {{ subCategory.title }}        
        {% endfor %}
    {% endfor %}
    

    If any doubt please comment.