Php Laravel提高了查询生成器的性能或说服力
对于多对多关系,我有以下表格(参考下图) 表名Php Laravel提高了查询生成器的性能或说服力,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,对于多对多关系,我有以下表格(参考下图) 表名申请,申请人,申请人申请 applications table id | stage | ------+---------------------------------------------------- 1 | 1 | 2 | 2 | . . . ___________________________________________________________ applic
申请
,申请人
,申请人申请
applications table
id | stage |
------+----------------------------------------------------
1 | 1 |
2 | 2 |
.
.
.
___________________________________________________________
applicants table
id | user_id |
------+--------------------------------------------------
1 | 27 |
2 | 12 |
.
.
.
___________________________________________________________
applicant_application table (pivot table for eloquent)
applicant_id | application_id |
-------------+-------------------------------------------
1 | 1 |
2 | 2 |
.
.
.
申请
和申请人
都是与申请人申请
applications table
id | stage |
------+----------------------------------------------------
1 | 1 |
2 | 2 |
.
.
.
___________________________________________________________
applicants table
id | user_id |
------+--------------------------------------------------
1 | 27 |
2 | 12 |
.
.
.
___________________________________________________________
applicant_application table (pivot table for eloquent)
applicant_id | application_id |
-------------+-------------------------------------------
1 | 1 |
2 | 2 |
.
.
.
我想做的是列出申请表中的所有阶段
及其相应的计数,但附加条件是信息在申请表中
这是我的查询生成器代码,我使用的是查询生成器,因为我不太确定如何用Elount实现它。你也会注意到我只画了第1阶段,第13阶段,一共有13个不同的阶段
$id = 27;
$stages = DB::query()
->select('apt.stage', DB::raw('count(apt.id) as count'))
->from('applications as apt')
->where('apt.stage', 1)->orWhere('apt.stage', 13)
->leftJoin('applicant_application as aa', 'aa.application_id', '=', 'apt.id')
->join('applicants as app', function($join) use ($id) {
$join->on('aa.applicant_id', 'app.id')
->where('app.user_id', $id);
})
->groupBy('apt.stage')
->orderBy('count', 'DESC')
->get();
return $stages;
上面的代码可以很好地处理以下输出
然而,我这里的主要问题是速度,加载似乎需要相当长的时间,我直接在SQL命令上运行了相同的查询,加载需要1.929秒
不要考虑我的数据库有500000多个申请者&500000多个申请记录,申请者的申请大约有700000个+
现在我的问题是,为了提高速度,实现这一目标的更好方法是什么?我怎样才能用雄辩的语言实现它呢
感谢您的帮助:)Eloquent不如原始查询快,DB::raw()将是最佳方式Eloquent不如原始查询快,DB::raw()将是最佳方式