使用Laravel 5.1中的结果对数据库查询进行内存缓存

时间:2015-12-09 12:23:47

标签: php caching laravel-5 memcached laravel-5.1

我想在memcache Laravel 5.1中查询结果。 当我使用下面的代码时,它显示一些错误和查询,结果没有放入缓存中。请参阅以下代码:

<?php

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use DB;

class Product extends Model
{
    public static function get_product_by_category($cat_id)
    {
        $result = array();
        $result = Cache::remember('get_product_by_category', 15/60, function() {
            $data = ModelProduct::join('products_images AS pimg', 'products.product_id', '=', 'pimg.pi_pid')
                                ->join('products_bridge AS pb', 'products.product_id', '=', 'pb.pb_product_id')
                                ->join('product_category_bridge AS pcb', 'pcb.pcb_product_id', '=', 'pb.pb_product_id')
                                ->where('pcb.pcb_cat_id',$cat_id)
                                ->where('products.product_status',1)
                                ->select('pcb.pcb_cat_id AS category_id','products.product_id AS product_id',
                                         'products.product_title AS product_name',DB::raw("COUNT(pb.pb_store_id) AS availibility_on_stores")
                                )->grouy('pb.pb_product_id')->get();    
            foreach($data as $value)
            {
                $result[$value->category_id][$value->product_id]["product_name"]=$value->product_name;
                $result[$value->category_id][$value->product_id]["product_availibility_on_stores"]=$value->availibility_on_stores;          
            }
            return $result;     
        });     
        return $result;
    }
}   
?>

错误: Undefined variable: cat_id

我使用以下参考资料: https://www.youtube.com/watch?v=PY09dDq5Mfw https://bosnadev.com/2014/12/27/laravel-caching-database-queries/

1 个答案:

答案 0 :(得分:1)

您传递给记住()的关闭无法访问 $ cat_id 变量 - 默认情况下,关闭只能访问 $ this 如果在对象上下文中执行引用,则需要使用 use 语句明确告知哪些变量应该从父作用域继承。

替换

$result = Cache::remember('get_product_by_category', 15/60, function() {

$result = Cache::remember('get_product_by_category', 15/60, function() use ($cat_id) {

有关详细信息,请参阅http://php.net/manual/en/functions.anonymous.php