我在Laravel中有这个查询,如何将其缓存10分钟?
$sorted_taxonomy_record = DB::select(
DB::raw(
'select level1.id as level1, level2.id as level2 from taxonomies as level1
left outer join taxonomies as level2 on level2.parent_id = level1.id
where level1.parent_id = ' . $taxonomy->id . ' order by level1, level2'
)
);
添加 - >记住(10)在它结束时不起作用。
答案 0 :(得分:1)
您可以使用Cache::remember
方法:
$sorted_taxonomy_record = Cache::remember('sorted_taxonomy_record', 10 , function()
{
return DB::select(
DB::raw(
'select level1.id as level1, level2.id as level2 from taxonomies as level1
left outer join taxonomies as level2 on level2.parent_id = level1.id
where level1.parent_id = ' . $taxonomy->id . ' order by level1, level2'
)
);
});
但建议使用query builder:
$sorted_taxonomy_record = DB::table('taxonomies as level1')
->select('level1.id as level1','level2.id as level2')
->join('taxonomies as level2', 'level2.parent_id', '=', 'level1.id', 'left outer')
->where('level1.parent_id','=',$taxonomy->id)
->orderBy('level1')
->orderBy('level2')
->remember(10,'sorted_taxonomy_record')->get();