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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据