kanazaca/counter-cache

Laravel 实现计数缓存包

1.0.1 2016-05-25 01:35 UTC

This package is not auto-updated.

Last update: 2024-09-28 19:03:54 UTC


README

Laravel 的计数缓存

为什么?

想象一下,如果您需要在列表中显示50个产品,并且还需要显示每个产品有多少个评论的计数,太多的查询,对吧?这个包将允许您极大地减少查询次数。

功能概述

  • 创建新记录时自动增加计数器。
  • 删除记录时自动减少计数器。
  • 更新记录时自动更新计数器。
  • ...

安装

将此添加到您的 composer.json 文件中的 require 对象

"kanazaca/counter-cache": "1.0.*"

之后,运行 composer install 安装包。将服务提供者添加到 config/app.php 文件中的 providers 数组。

'providers' => array(
	// ...
	kanazaca\CounterCache\CounterCacheServiceProvider::class,
)

基本用法

我将使用示例产品/评论,一个产品可以有多个评论

迁移

您需要在要访问计数的表中创建一个字段,如下例所示

Schema::create('products', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');
      $table->string('ref');
      $table->integer('comments_count')->default(0); // This is the counter that you have to add
      $table->timestamps();
  });

然后运行 php artisan migrate

模型

评论模型,您必须使用 trait,定义 $counterCacheOptions 并与产品建立关系

namespace App;

use Illuminate\Database\Eloquent\Model;
use kanazaca\CounterCache\CounterCache;

class Comments extends Model
{
    use CounterCache;

    // you can have more than one counter
    public $counterCacheOptions = [
        'Product' => ['field' => 'comments_count', 'foreignKey' => 'product_id']
    ];

    public function Product()
    {
        return $this->belongsTo('App\Product');
    }
}

过滤器

如果您想在计数缓存魔法发生之前进行一些过滤,您必须将 filter 键添加到 $counterCacheOptions 中,并使用字符串指定提供过滤的方法的名称,如下所示

public $counterCacheOptions = [
    'Product' => [
        'field' => 'comments_count',
        'foreignKey' => 'product_id',
        'filter' => 'CommentValidatedFilter'
    ]
]; // you can have more than one counter

// this code will be executed before the counting (save and update method)
public function CommentValidatedFilter()
{
    if ($this->validated) {
        return true;
    }

    return false;
}

致谢

Hugo Neto