Dev.W
Dev.W

Reputation: 2370

Eloquent Query On 2 Tables

Im getting the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'value' in 'where clause' (SQL: select sum(gross) as value, first_name from clients left join transactions on clients.id = transactions.client_id where value > 0 group by first_name)

From this function?

$data = DB::table('clients')->leftjoin('transactions','clients.id','=','transactions.client_id')
        ->select(DB::raw('sum(gross) as value, first_name'))
        ->where('value','>',0)
        ->groupBy('first_name')
        ->get();

return $data;

Upvotes: 1

Views: 74

Answers (1)

Rahul Patel
Rahul Patel

Reputation: 5246

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of sum(gross) to value has not yet occurred.

Aliases can be used in GROUP BY, ORDER BY, or HAVING clauses.

So instead of using value in where please use sum(gross) in where like below.

$data = DB::table('clients')->leftjoin('transactions','clients.id','=','transactions.client_id')
        ->select(DB::raw('sum(gross) as value, first_name'))
        ->where('sum(gross)','>',0)
        ->groupBy('first_name')
        ->get();

return $data;

Upvotes: 0

Related Questions