在Laravel中删除旧帖子类别后,将帖子移至“未归类"类别 [英] Move post to 'Uncategorized' Category when deleted old Category of post in Laravel

查看:57
本文介绍了在Laravel中删除旧帖子类别后,将帖子移至“未归类"类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a table to save post and category relationship.

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

如果我删除一个类别,我希望如果该帖子只有一个类别,则该类别的帖子将移至未分类"类别(ID = 1).

If I delete a category, I want posts of this category will move to 'Uncategorized' Category (with ID = 1) if post only have one a category.

这是我在CategoryController上的脚本:

This is my script at 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万个帖子,当我要删除类别时会非常慢.你能告诉我更好的主意吗?谢谢!

It working but I think it is'nt optimize. Because I must use the loop to find post only have one category. If I have 1 million posts, will very slow when I want delete a category. Can you show me better ideas? Thanks!

推荐答案

这可能会解决问题:

$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,并通过一个查询在数据库中对其进行了更新.

First you get the posts with count of their related categories in a single query. Then you filter only the posts with 1 or 0 categories. Finally you get their IDs and update them in the DB with a single query.

这篇关于在Laravel中删除旧帖子类别后,将帖子移至“未归类"类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆