减少分离标签的数量

时间:2013-07-09 18:33:53

标签: laravel laravel-4 eloquent

我有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

是否存在任何处理程序或shoud我合并数组并在旧集合中进行比较 - attachincrease,而不是在新集合中进行比较 - detachdecrease或completly另一种方式。

1 个答案:

答案 0 :(得分:0)

在我的个人博客中,我使用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在插入('已保存')到您的代码模型后更新计数。