首页 > 解决方案 > 我无法删除数据透视表中存在的记录

问题描述

我有五张桌子:

我遇到的问题是,如果我删除该帖子,那么它还应该删除该帖子在与其相关的所有表中的所有关系。但是系统正在执行完全相反的操作,它只是删除帖子表中的帖子。

我找到了一个解决方案

$table->engine='InnoDB'

但我的问题还是一样

这是我对 Category_post 数据透视表的迁移

public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('post_id')->index()->unsigned();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        $table->integer('tag_id')->index()->unsigned();
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        $table->timestamps();
    });
}

这就是我在控制器中所做的

public function destroy(Post $post)
{
    $post=Post::find($post->id);
    $post->delete();
    return redirect('admin/post')->with('message','Deleted Sucessfully');
}

我也试过这个

  public function destroy(Post $post)
{
    $post=Post::find($post->id);
    $post->categories()->delete();
    $post->tags()->delete();
    $post->delete();
    return redirect('admin/post')->with('message','Deleted Sucessfully');
}

但得到了相同的结果

标签: phpsqllaravelblogs

解决方案


在 Laravel 中为多对多关系使用数据透视表时,您应该将关联的标签和类别与 Post 模型分离,而不是按照文档
删除它们 此外,您的控制器代码正在删除标签和类别模型,而不是会破坏任何关联的关联附加到这些标签和类别的其他帖子。 这是在迁移
中正确执行此操作的示例
tags

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            // Any other columns goes here
            $table->timestamps();
        });
        Schema::create('post_tag', function (Blueprint $table) {
            $table->bigInteger('post_id');
            $table->bigInteger('tag_id');
            // ensures a specific post can be associated a specific tag only once
            $table->primary(['post_id', 'tag_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_tag');
        Schema::dropIfExists('tags');
    }

对类别迁移做同样的事情在你的 Eloquent 模型中
指定关系,如下所示ManyToMany

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

现在,当将标签/类别与帖子相关联时,请使用该attach方法

$post = Post::create([]); // this is only sample code, fill your data as usual
$tag = Tag::create([]);
$category = Category::create([]);
// You can either attach by the model itself or ID
$post->tags()->attach($tag);
$post->categories()->attach($category);

最后,在销毁 Post 模型时,只需将与标签和类别的关系解除关联,而不是使用detach 像这样的方法删除它们

public function destroy(Post $post)
{
   $post->categories()->detach();
   $post->tags()->detach();
   $post->delete();
   return redirect('admin/post')->with('message','Deleted Sucessfully');
}

推荐阅读