dongtaigan1594 2017-06-07 21:20
浏览 17
已采纳

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

When i delete a row from a groups table, i want the function to also delete all relation mapping from table group_user. For example, if i delete group with id 4, all rows in group_user table with group_id 4 are deleted as well. Tables below:

 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();
        });

Currently using this function in group controller, but it only deletes from groups table:

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

</div>
  • 写回答

1条回答 默认 最新

  • dpgf42422 2017-06-07 21:33
    关注

    If your table storage engine type is innodb you can try in your migrations to set correct relationships and all will be done in the database layer.

    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');
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面