Laravel 中大量数据查询有什么技巧吗

如题所述

->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));
foreach($posts as $p){
$data[] = array(
'id' => $p -> id,
'support' => $p -> support,
'against' => $p -> against,
'username'=> $p -> username,
'post_author' => $p -> post_author,
'post_title' => $p -> post_title,
'post_body' => $p -> post_body
);
}
$res = View::make('home.index')
-> with('posts', $data);
Cache::forever('staticPageCache_home', $res);
}
// 返回缓存的数据
return Cache::get('staticPageCache_home');
}
}
这里我用到了三个api
1). Cache::has ,这个判断是说如果当前不存在 staticPageCache_home 这个名字的缓存, 就立即去取数据
2). Cache::forever, 这个从用例文档里面可知是"永久缓存"的意思, 因为我一般都是很勤劳的,如果发表了博文,自己再去后台立即刷新一下缓存就好了, 所以不需要设置过期啊失效时间之类的, 当然这个是要按各自的具体需求来的
3). Cache::get , 这句是从缓存里面取出 staticPageCache_home 这个名字的缓存, 然后作为响应内容返回
嗯, 就这么简单, 呵呵, 一个基本的缓存功能就完成了, laravel的确是不错地!
3. 为后台添加刷新缓存功能
还是贴代码吧, 不过也很简单:
// 刷新首页缓存(暂时只支持首页)
public function get_refreshcache() {
/*
@var $GID admin组id
*/
$GID = 1;
if ( Auth::user() -> gid === 1 ) {
$data = array();
$posts = Post::with('user')
->join('users', 'users.id', '=', 'posts.post_author')
-> order_by('posts.created_at', 'desc')
->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));
foreach($posts as $p){
$data[] = array(
'id' => $p -> id,
'support' => $p -> support,
'against' => $p -> against,
'username'=> $p -> username,
'post_author' => $p -> post_author,
'post_title' => $p -> post_title,
'post_body' => $p -> post_body
);
}
$res = View::make('home.index')
-> with('posts', $data);
Cache::forever('staticPageCache_home', $res);
return '刷新首页缓存成功!';
}
return '对不起,只有管理员组才可进行此操作!';
}
我给后台添加了一个项目, 对应这个方法, 方法内容和首页的大同小异, 取数据, 然后Cache::forever 刷新一下缓存,就这么简单,当然了,上面的Auth::user() 判断是个简单的判断,只有管理员组才能进行刷新操作,呵呵
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-12-29
抓住特点查询
相似回答