dongtaigan1594 2017-06-07 13: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 13: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');
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部