2017-02-12 28 views
0

我想用雄辯的Laravel定義自定義中間表型號

,以獲取用戶權限我有3個表,

首先是用戶表,

二是所述權限

第三是user_permissions

的結構非常簡單

users 
-id 
-name 

permissions 
-id 
-name 

user_permissions 
-user_id 
-permission_id 
-read 
-write 
-update 
-delete 

這是顯示用戶權限的代碼:

$user = App\User::find(1)->first(); 
foreach($user->permissions as $permission){ 
    echo "Read".$permission->pivot->read."<br>"; 
    echo "Write".$permission->pivot->write."<br>"; 
    echo "Update".$permission->pivot->update."<br>"; 
    echo "Delete".$permission->pivot->delete."<br>"; 
} 

這一切工作正常,當我定義的關係這樣(在用戶模式) :

public function permissions() 
{ 
    return $this->belongsToMany('App\Permission','user_permissions')->withPivot('read', 'create','update','delete'); 
} 

但我想寫另一種方式,因爲我不想選擇我需要的字段我只是想選擇他們所有,所以當我把它寫這樣我得到一個錯誤:

public function permissions() 
{ 
    return $this->belongsToMany('App\Permission','user_permissions')->using('App\UserPermission'); 
} 

,這是我的錯誤:

BadMethodCallException在Builder.php線2440: 調用未定義的方法照亮\數據庫\查詢\生成器::使用()

+0

你有什麼Laravel版本? –

回答

0

I don't want to choose the fields that I need I just want to choose them all

如果你的意思是你不希望有指定哪些領域在樞軸存在,但也可自動發生 - 你不能。從the 5.2 docs

By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

Same is still true in 5.4

+0

這是我試圖在這裏做的:return $ this-> belongsToMany('App \ Permission','user_permissions') - > using('App \ UserPermission'); 但它不起作用 –

+0

我對「使用」方法不熟悉,在文檔中找不到任何有關它的信息......有哪些記錄? –

+0

這裏:https://laravel.com/docs/5.4/eloquent-relationships#many-to-many –

0

而不只是:

return $this->belongsToMany('App\Permission','user_permissions')->withPivot('read', 'create','update','delete'); 

您可以在透視模型中定義常量/變量:

class UserPermission extends Pivot 
{ 
    const PIVOT_ATTRIBUTES = [ 
     'read', 
     'create', 
     'update', 
     'delete' 
    ]; 

    // . . . 
} 

然後:

public function permissions() 
{ 
    return $this->belongsToMany(Permission::class, 'user_permissions') 
     ->withPivot(UserPermission::PIVOT_ATTRIBUTES) 
     ->using(UserPermission::class); 
} 

現在,您可以更新PIVOT_ATTRIBUTES不斷在你的UserPermission類。

+0

'使用(...)'僅在laravel 5.4,laravel 5中可用。3會給你'調用未定義的方法Illuminate \ Database \ Query \ Builder :: using()' –