2016-04-10 13 views
2

私は、この例ではuserとroleを使用して多対多の関係を作っています。 UserモデルでLaravel belongsToManyは片方向でしか動作しません。

私はこれだ:私は$user->roles()->attach(1);を行う際

public function up() 
    { 
     Schema::create('user_role', function(Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->integer('role_id')->unsigned(); 
      $table->timestamps(); 

      $table->foreign('role_id')->references('id')->on('roles'); 
      $table->foreign('user_id')->references('id')->on('users'); 
     }); 
    } 

public function users() 
{ 
    return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id'); 
} 

そして、私のピボットテーブルUSER_ROLE:私はこれを得た役割モデルで

public function roles() 
{ 
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id'); 
} 

をuser_roleテーブルに行が作成されます。しかし、問題は私がそれにアクセスしたいときです:$user->roles;何も返しません。 $role->users;で動作しますが、それ以外の方法では動作しません。私は間違って何をしていますか?

+0

私はLaravelについては知らないが、2つのテーブル間の「多対多の関係」の表を作成し、使用しなければならないように取り付けた後に関係をリロードする必要があります。 –

+0

私はLaravelのドキュメントから取られた多対多のリレーションシップの例を使用しています。https://laravel.com/docs/5.2/eloquent-relationships#many-to-many – user3743266

答えて

1

は解決:Laravel 5.2.29

は、テーブル名が、これはあなたのために働くROLE_USER

$user = User::find(1); 
    $role = Role::find(2); 
    // In this example I am passing in a Role object but $role->id also works 
    $user->roles()->attach($role); 

希望であることを確認してください。

+0

私はuser_roleとrole_userの両方のテーブル名を試しましたが、それと同じ問題です。この2番目のパラメータはテーブル名を意味し、3番目は現在のモデル行を意味し、4番目はモデル行名をアタッチしたことを意味します – user3743266

+0

私が作成したモデルの名前は '' AppToMany( 'App \ User'、 'user_role'、 'role_id'、 'user_id'あなたのためにレポ。次のレポをクローンします:[https://github.com/HashmatWaziri/laravel-5.2.29-manyToManyRelationship](https://github.com/HashmatWaziri/laravel-5.2.29-manyToManyRelationship) – user2592890

0

あなたはそう

$user->roles()->attach($role); 

$user->load('roles'); 
関連する問題