【问题标题】:Decrease count of detached tags减少分离标签的数量
【发布时间】:2013-07-09 18:33:52
【问题描述】:

我有 PostTag 模型

为了给帖子添加标签,我有:

public function addTag($tag) // $tag is string
{
    $slug = Str::slug($tag);

    $t = Tag::where("url", $slug)->first();

    if(!$this->in_array_field($slug, 'name', $this->tags))
    {
        if(!isset($t))
        {
            $t = new Tag;
            $t->name = $tag;
            $t->url = $slug;
            $t->count = 1;
        }
        else
        {
            $t->increment('count');
        }

        $this->tags()->save($t);
    }

    return $t->id;
}

添加所有标签后,我调用sync 来删除集合中不再存在的标签

$this->tags()->sync($tagsIds); // $this is Post model

一切正常,但如何减少分离标签count

是否有任何处理程序或者我应该合并数组并比较,如果不在旧集合中 - attachincrease,不在新集合中 - detachdecrease 或完全以另一种方式。

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    在我的个人博客中,我使用 sql 来获取计数(我的标签数量相对较少,因此开销较低 + 加上我缓存了结果):

    // Get list of tags, ordered by popularity (number of times used)
    return \DB::table('tags_articles')->select('name', 'url_name', 'tag_id', \DB::raw('count(`tag_id`) as `tag_count`'))
                   ->join('tags', 'tags.id', '=', 'tags_articles.tag_id')
                   ->groupBy('tag_id')
                   ->orderBy('tag_count', 'DESC')
                   ->take($limit)
                   ->get();
    

    或者,您可能希望运行单独的查询来更新与该进程分开的每个标签计数 - 在 cron 中,或者在调用 sync() 之后运行新查询。假设您的写入量很少(通常每秒不会多次标记项目),无论哪种方式可能都不会导致太多瓶颈。

    最后,数据库更新后会触发“事件”。看看其中一些model events 是否可用于在将插入(“保存”)到您的标签模型后更新计数。

    【讨论】:

    • 恕我直言,这都不是优雅的解决方案,但是谢谢,也许我会使用一些东西
    • 您的用例中的理想情况是什么?或许还有待改进。
    • 我已经通过foreach($this->tags as $tag) { if(!in_array($tag->name, $tags)) { $this->tags()->detach($tag->id); $tag->decrement('count'); } } 解决了它 - 如果所有标签之一不在 $tags 中(从输入设置),它的分离和递减
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多