繁体   English   中英

Laravel 5.4删除表行和相关表中的行

[英]Laravel 5.4 delete table row and rows from related table

当我从组表中删除一行时,我希望函数也从表group_user中删除所有关系映射。 例如,如果我删除ID为4的组,则同时删除了group_id为4的group_user表中的所有行。 下表:

  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){ $group = Group::find($id); $group->delete(); return redirect()->back(); } 

如果您的表存储引擎类型为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');
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM