Builder plugin how to display items selected by another model class instead of all items?

213 views Asked by At

I build my own plugin with octoberCMS Builder plugin. There are 2 different model classes

  1. category
  2. item

inside the model class "item" I have a relation to model class category so each item can be linked to a "category".

On my webpage, I would like to display model class category and inside all items from model class "item" that are linked to that category.

however, all items are displayed now instead of the ones linked to category. My thought was to use the == sign but that's not working so far. How can I solve this issue? Help would be highly appreciated!

explanation of my question what my page looks like

1

There are 1 answers

0
Hardik Satasiya On BEST ANSWER

May be you can utilize parent child relation ship.

In your Category model add relationship

class Category extends Model
{
    // we consider item table has `category_id` field to maintain relationship  
    public $hasMany = [
        'items' => ['Yournamespace\Item']
    ];
}

now all you can so is fetch Categories

$categories= Category::all();
// pass $categories to view

now loop through category and its items

<ul>
    {% for category in categories%}
        <li>
            <h3> {{ category.name }} </h3>
            <ul>
                {% for item in category.items %}
                    <li>{{ item.name }}</li>
                {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

It will show list of categories as main list and each list have sub-list as it's items

if any doubts please comment.