今天分享使用tp6框架将30万表数据查询从2秒优化到100多毫秒的方法,若大佬还有更好方案,还往指教一、二,废话不多说直接上代码。
我们使用tp6框架中一对一关联,如果有同学不懂一对一关联,还望自行去查看文档,具体步骤如下:
一、给建立的表加入索引
二、创建一对一表关联model
class GoodsEvaluate extends model{
//关联商品表
public function goodsProfile()
{
return $this->hasOne(Goods::class,'id','goods_id');
}
//关联用户表
public function userProfile(){
return $this->hasOne(User::class,'id','uid');
}
}
三、在控制器进行一对一表的查询
$list = GoodsEvaluate::field('create_time,id,goods_id,uid,verify_status,is_selected,content')
->with(['goodsProfile'=>function($goods_query) use ($goods_name){
if (empty($goods_name)) {
$goods_query->field('id,name');
}else{
$goods_query->where('name','like','%'.$goods_name.'%')->field('id,name');
}
},'userProfile'=>function($user_query) use ($user_name){
if (empty($user_name)) {
$user_query->field('id,user_name');
}else{
$user_query->where('user_name','like','%'.$user_name.'%')->field('id,user_name');
}
}])
->order('id DESC')
->paginate(['list_rows' => $this->page_num, 'page' => $this->page])
->toArray();
注:“use”是获取外围传入的值
最后给大家看看测试的结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/d2cd1f2b1df24509a8a0d9a78097b948.png