2016-03-06 86 views
5

我有兩個以下2種型號在許多一對多的關係:保存多對多的關係,sync/attach不存在?

use Illuminate\Database\Eloquent\Model; 

class Permission extends Model 
{ 
    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'permissions'; 

    /* 
    |-------------------------------------------------------------------------- 
    | Relationship Methods 
    |-------------------------------------------------------------------------- 
    */ 

    /** 
    * many-to-many relationship method 
    * 
    * @return QueryBuilder 
    */ 
    public function roles() 
    { 
     return $this->belongsToMany('App\Admin\Role'); 
    } 

} 

class Role extends Model 
{ 
    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'roles'; 

    /* 
    |-------------------------------------------------------------------------- 
    | Relationship Methods 
    |-------------------------------------------------------------------------- 
    */ 

    /** 
    * many-to-many relationship method. 
    * 
    * @return QueryBuilder 
    */ 
    public function users() 
    { 
     return $this->belongsToMany('App\Admin\User'); 
    } 

    /** 
    * many-to-many relationship method. 
    * 
    * @return QueryBuilder 
    */ 
    public function permissions() 
    { 
     return $this->belongsToMany('App\Admin\Permission'); 
    } 
} 

我想在這裏做的,就是創建一個網頁,新角色可以創建,並將該角色與已創建的權限關聯:

@foreach ($permissions as $permission) 
          <label class="checkbox"> 
           <input type="checkbox" value="{{ $permission->id }}" name="permissions[]" id="permission_{{ $permission }} }}"> 
           {{ $permission->permission_title }} 
          </label> 
         @endforeach 

並在控制器中我試圖從網頁中提取選定的權限並保存每一個事情:

// logic to save role 
$role->save(); 
$permissions = Input::get('permissions'); 
$role->permissions->sync($permissions); 

的最後一條語句執行我收到以下錯誤但是經過: exception 'BadMethodCallException' with message 'Method sync does not exist.' 同樣的錯誤,我得到了attach爲好。另外,我不確定我是否應該提供中間表permission_role的名稱?謝謝。

回答

9

您需要使用以下方法:

$role->permissions()->sync($permissions); 

不要忘了()

編輯:一些更多的解釋:

$role->permissions是一家集實例。

$role->permissions()belongsToMany實例,它包含了sync()方法

+0

它也沒有用'()' –

+2

不,不我只是測試,並得到了確切的同樣的錯誤是不帶'()'。這是因爲'$ role-> permissions'是一個Collection實例,'$ role-> permissions()'是一個包含'sync()'方法的belongsToMany實例:) – Hammerbot

+0

謝謝,就是這樣。 – Zed