我无法删除数据透视表中存在的记录

时间:2019-08-24 16:14:20

标签: php sql laravel blogs

我有五个表:

  • 发布
  • 类别
  • 标签
  • category_post
  • post_tag

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

我找到了一个解决方案

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

但是得到了相同的结果

1 个答案:

答案 0 :(得分:2)

在Laravel中将数据透视表用于ManyToMany关系时,应使用Post模型分离关联的标签和类别,而不要按照docs
删除它们 此外,您的控制器代码正在删除标签和类别模型,而不是关联,因为关联将破坏附加到这些标签和类别的任何其他帖子。
这是正确方法的示例
在您的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');
    }

对类别迁移执行相同的操作
像这样

在口才模型中指定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');
}