ManyToMany relation: belongsToMany

manytomanyはpivotテーブルを使って、子供のレコードを管理する

$ php artisan make:model Role -m
$ php artisan make:migration create_role_user_table –create=role_user

role_user

Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable()->index();
            $table->integer('role_id')->unsigned()->nullable()->index();
            $table->timestamps();
        });

role

 Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

$ php artisan migrate

User.php

public function roles(){

        return $this->belongsToMany('App\Role');
    }

Role.php

class Role extends Model
{
    //
    protected $fillable = ['name'];
}

insert into users (name, email, password) values (‘peter’, ‘peter@gmail’, ‘1234’);

Route::get('/create', function(){
	$user = User::find(1);

	$role = new Role(['name'=>'adminstrator']);

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

});

mysql> select * from role_user;
+—-+———+———+————+————+
| id | user_id | role_id | created_at | updated_at |
+—-+———+———+————+————+
| 1 | 1 | 1 | NULL | NULL |
+—-+———+———+————+————+
1 row in set (0.00 sec)

read

Route::get('/read', function(){
	$user = User::findOrFail(1);

	foreach($user->roles as $role){
		dd($role);
	}
});

update
has()で確認する


Route::get('/update', function(){

	$user = User::findOrFail(1);

	if($user->has('roles')){

		foreach($user->roles as $role){
			if($role->name == 'adminstrator'){
				$role->name = 'Adminstrator';
				$role->save();
			}
		}
	}
});

delete

Route::get('/delete', function(){

	$user = User::findOrFail(1);

	$user->roles()->delete();

});

attach & delete

Route::get('/attach', function(){

	$user = User::findOrFail(1);

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

});

Route::get('/detach', function(){

	$user = User::findOrFail(1);

	$user->roles()->detach(2);

});

createだけでなく、attachとdeleteがあるってのは、理にかなってます。