通过hasMany获取父表上的where子句获取子表数据

Framework

Laravel 5.1

Objectives

  1. Get all buttons for all button_sets where template_id = $id ($id is passed into the controller method when called)

  2. (Two options) (1) Pass two arrays, modules and buttons. (2) Pass a multidimensional array with modules and buttons as two keys with underlying data. Both options retrieved based on the id of the template.

Table structure

modules

name         | type
-----------------------
id           | int(10)
name         | varchar(255)
header       | varchar(255)

templates

name         | type
-----------------------
id           | int(10)
name         | varchar(255)

button_sets

name         | type
-----------------------
id           | int(10)
name         | varchar(255)
templates_id | int(10) (FK with 'id' on 'templates')
modules_id   | int(10) (FK with 'id' on 'modules')

buttons

name           | type
-----------------------
id             | int(10)
name           | varchar(255)
button_sets_id | int(10) (FK with 'id' on 'button_sets')

Relationships

class ButtonSet extends Model
{
    public function buttons()
    {
        return $this->hasMany('App\Button', 'button_sets_id', 'id');
    }
}

Controller method

public function show($id)
{
    switch ($id) {
        case 1:
            $mod = Module::all()->toArray();
            $buttons = ButtonSet::with('buttons')->get()->toArray();
            $modules = $this->array_merge_recursive_distinct($mod, $buttons);

            return view('index', compact('modules'));
    }
}

Attempts and questions

Objective 1

As you can see in the Controller Method I have tried to use Eager Loading(think this is the way to go) and was able to successfully retrieve a multidimensional array of all button_sets with their buttons using the following code: $buttons = ButtonSet::with('buttons')->get()->toArray();. I still need to say where template_id = $id... How do I do this?

Objective 2 [SOLVED]

I then tried to merge the above array with the modules array using this which worked very nice. While this resulted in a multidimensional array without to much nested arrays I still am not able to say I'm now unable to pull any data from it in the view, using my foreach loop above, getting error Trying to get property of non-object. What needs to change here? Successfully retrieved the data from the merged array.

Is there a easier way to achieve all of this?

I've tried to wrap my mind around polymorphic relations but I'm so new to PHP, OOP and Laravel this just goes beyond my understanding at this time..

Please tell me if you need further data to understand my challenges.

Very thankful if someone can point me in the right direction!