php - 具有 4 个表的查询生成器
问题描述
这是我的查询生成器功能:
public function MonthSoldGDV($dev,$year){
$monthlyGDV = DB::table('pams_unit')
->join('pams_phase','pams_unit.phase_id','pams_phase.phase_id')
->join('pams_project','pams_phase.project_id','pams_project.project_id')
->join('pams_developer','pams_project.dev_id ','pams_developer.id')
->select('pams_developer.developer_name')
->selectRaw('year(pams_unit.sold_date) as year')
->selectRaw('month(pams_unit.sold_date) as month')
->selectRaw('sum(pams_unit.sold_price) as gdv')
->where('pams_developer.developer_name','$dev')
->whereRaw('year(sold_date) = $year')
->groupBy('month')
->get();
return $monthlyGDV;
}
但它显示一个错误Column not found: 1054 Unknown column '$year' in 'where clause'
有人可以帮我找出我的问题吗?
解决方案
有时您可能需要在查询中使用原始表达式。要创建原始表达式,您可以使用 DB::raw 方法:
在您的情况下,'$year'
PHP 认为这'$year'
是一个string
字符,而不是变量,并且whereRaw
含义使用原始表达式。这是你错误的原因
$monthlyGDV = DB::table('pams_unit')
->join('pams_phase', 'pams_unit.phase_id', '=', 'pams_phase.phase_id') //changed
->join('pams_project', 'pams_phase.project_id', '=', 'pams_project.project_id') //changed
->join('pams_developer', 'pams_project.dev_id ', '=', 'pams_developer.id') //changed
->select('pams_developer.developer_name')
->selectRaw('year(pams_unit.sold_date) as year')
->selectRaw('month(pams_unit.sold_date) as month')
->selectRaw('sum(pams_unit.sold_price) as gdv')
->where('pams_developer.developer_name', $dev) //changed
->where(DB::raw('year(sold_date)'), $year) //changed
->groupBy('month')
->get();
编辑:
public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
{
// If the first "column" of the join is really a Closure instance the developer
// is trying to build a join with a complex "on" clause containing more than
// one condition, so we'll add the join and call a Closure with the query.
if ($one instanceof Closure) {
$join = new JoinClause($type, $table);
注意第三个参数是$operator
,所以你应该做这样的事情
join('pams_developer', 'pams_project.dev_id ', '=', 'pams_developer.id')
推荐阅读
- symfony - Symfony Doctrine - 将 CTE 与查询构建器一起使用
- scala - 如何计算 Scala 混合对象序列中的每种类型/种类的对象
- excel - 应用过滤器后如何选择第二个可见行
- java - AWS EC2 Linux 实例 - 合适的文件夹位置来存储经常被 Web 服务器更新和读取的文件
- javascript - 如何从 performance.window.performance.timing 输出中获取性能 KPI?
- javascript - 创建后如何访问某些div类
- javascript - Swagger 编辑器中的 Swagger ui json 导入给出错误:Undocumented TypeError: Failed to fetch on making API calls
- python - How to perform lowpass filtering in RGB images with Discrete Wavelet Transform in Python
- r - Summarise - Error: `n()` must only be used inside dplyr verbs
- java - 如何在java中的一行中显示两个变量输出?