문제

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

도움이 되었습니까?

해결책

The problem would be properly setting your primary keys in your models..

Each model needs this with relevant key name.

public $primaryKey = 'primarykeyname'

Additionally, appropriate way to eagler load would be to use it like so...

$menuItems = MenuItem::with('role')->get();

다른 팁

try loading the relations with eager loading.

$menuItems = MenuItem::with('role')->get();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top