Reputation: 3854
I have two table one is for role and other for its permission i want to delete role permission when i delete role. For that i have linked role table with role permission with the help of below code in migration, but it is not deleting data from role permission.
class Role extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->foreign('id')->references('role_id')->on('role_permission')->onDelete('cascade');
});
}
Role Permission :
class CreateRolePermission extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_permission', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('role_id');
$table->integer('module_id');
$table->integer('permission');
});
}
Upvotes: 0
Views: 68
Reputation: 29
Remove it from role migration
$table->foreign('id')->references('role_id')->on('role_permission')->onDelete('cascade');
and add it inside in CreateRolePermission like this
class CreateRolePermission extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_permission', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('role_id'); $table->integer('module_id'); $table->integer('permission'); $table->foreign('role_id')->references('id')->on('role')->onDelete('cascade'); }); }
Upvotes: 0
Reputation: 193
I think you have created foreign key in wrong table
just remove
$table->foreign('id')->references('role_id')->on('role_permission')->onDelete('cascade');
from role migration and add
$table->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
in role_permission migration
Upvotes: 1
Reputation: 558
You put the foreign constraints in the wrong order.
It should be the role_permission
references to the role
by id
through role_id
, like this:
// inside CreateRolePermission
$table->foreign('role_id')
->references('id')
->on('role')
->onDelete('cascade');
Also, delete the foreign
in the role
table
Upvotes: 1