在laravel

时间:2018-06-02 07:13:03

标签: php mysql laravel laravel-5 migration

这是我的帖子表

   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');


            });
        }

这是我的用户表

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

这些是关系

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

public function user() {
        return $this->belongsTo('App\User');
    }

删除用户代码

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

删除帖子的代码

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');

    }

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

4 个答案:

答案 0 :(得分:7)

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

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

$table->engine = 'InnoDB';

或用

更改表格
ALTER TABLE table_name ENGINE=InnoDB;

可以帮到你。

答案 1 :(得分:0)

创建自定义方法,例如function destroyAllByUser()

并输入类似

的代码
DB::table('posts')->where('user_id', '=', 1)->delete();

我希望它可以提供帮助

答案 2 :(得分:0)

删除用户;

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

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

    $user->posts->delete();

    $user->delete();

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

    return redirect('/admin/users');
}

答案 3 :(得分:0)

另一种解决方法是将laravel-project \ config文件夹下的database.php文件配置为在InnoDB引擎上工作。

'mysql' => [
   ...

   'engine' => 'InnoDB'
 ]

现在,您在使用外键时无需担心... 记住-如果在创建表之前未配置此设置,则应再次迁移。

相关问题