Wallogit.com
2017 © Pedro Peláez
Counter Cache for Laravel 5
Package Counter Cache for Laravel 5, (*1)
composer require quankim/laravel-counter-cache
I will use the example products/comments, one product have many comments, (*3)
Table products:, (*4)
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('comments_count')->default(0);
$table->float('rating_average', 15, 1)->nullable();
$table->timestamps();
});
Table comments:, (*5)
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->string('content');
$table->integer('rating_value')->nullable();
$table->timestamps();
});
Model Product:, (*6)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Comment;
class Product extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function ratingAverage()
{
return round($this->comments()->avg('rating_value'), 1);
}
}
Model Comment:, (*7)
<?php
namespace App\Models;
use QuanKim\LaravelCounterCache\Traits\CounterCache;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product;
class Comment extends Model
{
use CounterCache;
public $counterCacheOptions = [
'product' => [
'comments_count' => [],
'rating_average' => [
'method' => 'ratingAverage',
],
],
];
public function product()
{
return $this->belongsTo(Product::class);
}
}
if you use boot() function in Model Comment, you must define as below:, (*8)
use CounterCache {
boot as preBoot;
}
protected static function boot()
{
self::preBoot();
// ...
}
public $counterCacheOptions = [
'product' => [
'comments_count' => [],
'rating_average' => [
'method' => 'ratingAverage',
'conditions' => [
'is_publish' => true,
],
],
],
];
Vo Hong Quan, (*9)