首页 > 解决方案 > 在 Laravel 中删除旧帖子类别时将帖子移动到“未分类”类别

问题描述

我创建了一个表格来保存帖子和类别的关系。

Schema::create('post__post_category_relations', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('post_id')->unsinged();
        $table->integer('category_id')->unsinged();
    });

如果我删除一个类别,如果帖子只有一个类别,我希望此类别的帖子将移动到“未分类”类别(ID = 1)。

这是我在 CategoryController 的脚本:

 public function destroy(Category $category)
{

    $this->category->destroy($category);

    foreach($category->posts as $post){
        if(count($post->categories) <= 1){
            PostCategoryRelations::where('post_id',$post->id)->update(['category_id' => 1]);
        }
    }
}

和类别型号:

public function posts()
{
    return $this->belongsToMany(Post::class, 'post__post_category_relations', 'category_id');
}

和帖子模型:

public function categories()
{
    return $this->belongsToMany(Category::class, 'post__post_category_relations', 'post_id');
}

它工作,但我认为它不是优化。因为我必须使用循环来查找帖子只有一个类别。如果我有 100 万个帖子,当我想删除一个类别时会很慢。你能告诉我更好的想法吗?谢谢!

标签: phplaravel

解决方案


这可能会奏效:

$postsOfCategory = $category->posts()->withCount('categories')->get();
$postsWithOneCategory = $postsOfCategory->filter(function ($post) {
    return $post->categories_count <= 1;
});
$postsIDs = $postsWithOneCategory->pluck(['id'])->toArray();

PostCategoryRelations::whereIn('post_id', $postsIDs)->update(['category_id' => 1]);

首先,您在单个查询中获得具有相关类别计数的帖子。然后您只过滤具有 1 或 0 类别的帖子。最后,您获得他们的 ID 并通过单个查询在数据库中更新它们。


推荐阅读