这是我的查询构建器功能:
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'
有人可以帮我弄清楚我的问题吗?
答案 0 :(得分:0)
有时您可能需要在查询中使用原始表达式。要创建原始表达式,可以使用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')