laravel eloquent, many to many, custom column names, what am I doing wrong

StackOverflow https://stackoverflow.com/questions/23138956

  •  05-07-2023
  •  | 
  •  

سؤال

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