menuitem:
Id int
MenuLevel int
Label varchar(50)
Controller varchar(50)
Action varchar(50)
ParentId int
role:
Id int
Name varchar(50)
menurole:
MenuRoleId int (primary key)
RoleId int (foreign key to Role)
MenuItemId int (foreign key to MenuItem)
I am trying to retrieve all menu items and to display them in a table, and to display all the roles that each menu item has as a comma separated list in a single table cell.
My models:
class MenuItem extends Eloquent
{
protected $table = 'menuitem';
public $timestamps = false;
public function roles()
{
return $this->belongsToMany('Role', 'menurole', 'MenuItemId', 'RoleId');
}
}
class Role extends Eloquent
{
protected $table = 'role';
public $timestamps = false;
public function menuItems()
{
return $this->belongsToMany('MenuItem', 'menurole', 'RoleId', 'MenuItemId');
}
}
Code that prepares the data for the view in controller looks like this:
$menuItems = MenuItem::all();
All that is done in the view is double foreach loop. One to get all menu items, and the other one to get all the roles for every menu item.
@foreach ($menuItems as $item)
@foreach ($item->roles as $role)
<span>{{ $role->Name }}</span>
@endforeach
@endforeach
The problem is that there are no roles retrieved. Menu items are there. Renaming db columns is not an option for now. What am I doing wrong ?
EDIT:
Running on WAMP, MySql version 5.6.12