删除laravel中与用户相关的所有帖子

Moh*_*rma 2 php mysql migration laravel laravel-5

这是我的帖子表

   public function up()
        {
            Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('user_id');
                $table->integer('category_id')->unsigned()->index();
                $table->integer('photo_id')->default(0)->unsigned()->index();
                $table->string('title');
                $table->text('body');
                $table->timestamps();

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


            });
        }
Run Code Online (Sandbox Code Playgroud)

这是我的用户表

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('role_id')->index()->unsigned()->nullable();
            $table->integer('photo_id')->index()->default(0);
            $table->boolean('is_active')->default(0);
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
Run Code Online (Sandbox Code Playgroud)

这些是关系

 public function posts() {
        return $this->hasMany('App\Post');
    }

public function user() {
        return $this->belongsTo('App\User');
    }
Run Code Online (Sandbox Code Playgroud)

删除用户的代码

public function destroy($id)
    {
        $user = User::findOrFail($id);

        if($user->photo_id !== 0) {
            unlink(public_path() . $user->photo->path);
        }


        $user->delete();

        Session::flash('deleted_user', 'The user has been deleted.');

        return redirect('/admin/users');
    }
Run Code Online (Sandbox Code Playgroud)

删除帖子的代码

public function destroy($id)
    {
        $post = Post::findOrFail($id);

        if($post->photo_id !== 0) {
            unlink(public_path() . $post->photo->path);
        }


        $post->delete();

        return redirect('/admin/posts');

    }
Run Code Online (Sandbox Code Playgroud)

我在删除用户时尝试删除与用户相关的所有帖子.为此,我在posts表中使用外部引用约束,如上所示但是当我删除用户时它不起作用.这些帖子仍在那里.我不知道我做错了什么

小智 7

出现此问题的可能原因很可能是因为MySQL实例中的默认表引擎设置为不支持外键的MyISAM.尝试在MyISAM表上使用外键肯定不会是Laravel中的错误.虽然如果使用外键,Schema Builder可以自动将引擎设置为InnoDB,这样会很好.

所以,在你的架构中使用这一行

$table->engine = 'InnoDB';
Run Code Online (Sandbox Code Playgroud)

或改变表格

ALTER TABLE table_name ENGINE=InnoDB;
Run Code Online (Sandbox Code Playgroud)

可能会帮到你.