2013-01-12 63 views
0

我有2個表和一個數據透視表。表格的結構在下面提到。使用laravel從多個檢索數據到多個

users table: 
id username password 
1 admin xyzasd 

roles table: 

id name 
1 role1 
2 role2 

role_user table: 

id user_id role_id 
1 1  1 
2 1  2 

我的用戶模型:

class User extends Basemodel{ 
    public static $table = 'users'; 
    public static $timestamps = true; 

    public function roles() 
    { 
     return $this->has_many_and_belongs_to('Role'); 
    } 

    public static function menu(){ 
     $roles = User::find(1)->roles()->get(); 
     return $roles; 
    } 
} 

我的控制器:

public function get_index() 
    { 
     return View::make('home.index') 
      ->with('title','testing many to many') 
      ->with('menu',User::menu()); 
    } 

,並在我的刀片查看文件我有這個聲明{{$菜單}}所有我得到的是一個消息數組,有人可以指導我如何獲取記錄嗎?

回答

3

首先,用戶應擴展侃侃而談。另外,你應該創建一個角色模型。

//application/models/User.php

class User extends Eloquent 
{ 
    public static $table = 'users'; 
    public static $timestamps = true; 

    public function roles() 
    { 
     return $this->has_many_and_belongs_to('Role'); 
    } 
} 

//application/models/Role.php

class Role extends Eloquent 
{ 
    public static $table = 'roles'; 
    public static $timestamps = true; 

    public function users() 
    { 
     return $this->has_many_and_belongs_to('User'); 
    } 
} 

然後爲您的控制器,你基本上可以只傳遞給用戶。

public function get_index() 
{ 
    $user = User::find(1); 

    return View::make('home.index') 
     ->with('title','testing many to many') 
     ->with('user', $user); 
} 

然後在您的視圖,你可以做很酷的東西,如:

<h1>What's up {{ $user->username }}?</h1> 
<h2>You have the following roles:</h2> 
@foreach($user->roles as $role) 
    <p>{{ $role->name }}</p> 
@endforeach 
+0

我已延長我Basemodel雄辯類。 :)但真的很感謝你的幫助:) –

1

你應該遍歷數組$menu在您的視圖:

@foreach ($menu as $menu_item) 
    {{ $menu_item->id }} # output ID of a record 
@endforeach