2017-06-07 77 views
0

当我从组表中删除一行时,我想要该函数也从表group_user中删除所有关系映射。例如,如果我删除了id为4的组,group_user表中group_user表中的所有行也会被删除。如下表:Laravel 5.4从相关表中删除表行和行

Schema::create('users', function (Blueprint $table) { 
 
      $table->increments('id'); 
 
      $table->string('name'); 
 
      $table->string('email')->unique(); 
 
      $table->string('password'); 
 
      $table->string('phone'); 
 
      $table->boolean('approved')->default(false); 
 
      $table->rememberToken(); 
 
      $table->timestamps(); 
 
     }); 
 
Schema::create('groups', function (Blueprint $table) { 
 
      $table->increments('id'); 
 
      $table->string('name'); 
 
      $table->integer('course_id'); 
 
      $table->timestamp('start_date')->nullable(); 
 
      $table->timestamp('end_date')->nullable(); 
 
      $table->timestamps(); 
 
     }); 
 
    Schema::create('group_user', function (Blueprint $table) { 
 
      $table->increments('id'); 
 
      $table->integer('user_id'); 
 
      $table->integer('group_id'); 
 
      $table->timestamps(); 
 
     });

目前使用组控制这个功能,但它只能从组表中删除:

function deleteGroup($id){ 
 
\t \t $group = Group::find($id); 
 
\t \t $group->delete(); 
 
\t \t return redirect()->back(); 
 
\t }

+1

我想你想的一些定义,如:'$表 - >外国( 'USER_ID') - 上( 'gropu')> - - >引用( '身份证')> onDelete( '串联'); ' – mkaatman

+0

@mkaatman抱歉,我没有看到您的评论;)我认为您的评论是正确的解决方案。 –

回答

1

如果你的表存储引擎type是innodb,你可以尝试在你的迁移中设置正确的关系并且全部将在数据库层完成。

Schema::create('group_user', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('user_id'); 
     $table->integer('group_id'); 
     $table->timestamps(); 

     $table->foreign('user_id') 
       ->references('id') 
       ->on('users')) 
       ->onDelete('cascade'); 
     $table->foreign('user_id') 
       ->references('id') 
       ->on('users')) 
       ->onDelete('cascade'); 
    }); 
+0

我的数据库是mariadb,它还能工作吗?谢谢 – Benua

+0

InnoDB是一个数据库管理系统(MySQL,MariaDB)的存储引擎,但如果我没有错误的laravel默认使用innoDB进行迁移。 –