私は、この例では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;
で動作しますが、それ以外の方法では動作しません。私は間違って何をしていますか?
私はLaravelについては知らないが、2つのテーブル間の「多対多の関係」の表を作成し、使用しなければならないように取り付けた後に関係をリロードする必要があります。 –
私はLaravelのドキュメントから取られた多対多のリレーションシップの例を使用しています。https://laravel.com/docs/5.2/eloquent-relationships#many-to-many – user3743266