2013-01-12 5 views
0

2 테이블과 피벗 테이블이 있습니다. 테이블의 구조는 다음과 같습니다. laravel을 사용하여 many에서 many로 데이터를 검색

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 //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'); 
    } 
} 

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

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

그런 다음 컨트롤러에 대한 당신은 기본적으로 단지 사용자에게 전달할 수 있습니다. 난 내 BASEMODEL의 웅변 클래스를 확장 한

<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

: 같은

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

그런 다음보기에 당신은 멋진 물건을 할 수 있습니다. :)하지만 정말 당신의 도움에 감사드립니다 :) –

1

당신은보기에 $menu 이상의 배열을 반복해야합니다

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