Php 删除Laravel中旧类别的帖子时,将帖子移至“未分类”类别

Php 删除Laravel中旧类别的帖子时,将帖子移至“未分类”类别,php,laravel,Php,Laravel,我创建了一个表来保存帖子和类别的关系 Schema::create('post__post_category_relations', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->integer('post_id')->unsinged(); $table->integer('category_id')->unsinged();

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

Schema::create('post__post_category_relations', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('post_id')->unsinged();
        $table->integer('category_id')->unsinged();
    });
如果我删除了一个类别,我希望该类别的帖子将移动到ID=1的“未分类”类别,如果帖子只有一个a类别

这是我在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 categories()
{
    return $this->belongsToMany(Category::class, 'post__post_category_relations', 'post_id');
}

它在工作,但我觉得不是很好。因为我必须使用循环来查找只有一个类别的帖子。如果我有一百万篇文章,当我想删除一个类别时,速度会非常慢。你能告诉我更好的主意吗?谢谢

这可能会奏效:

$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并在数据库中更新它们

$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]);