Compare result query SQL Laravel with Int

1

I am programming in Laravel 5.5 and I need to compare a query with an integer to perform a verification. The code is as follows:

$sum_=DB::table('eventos_tienen_trabajadores as ett')
   ->where('ett.id_trabajador', '=', $id)
   ->where('ett.estado', '=', '1')
   ->select(DB::raw('sum(monto) as sum'))
   ->get();

   if($sum_ == 0){...

Of course it is not possible to compare it, so I would like to know how I can do this efficiently.

    
asked by José Antonio Pedraza 26.01.2018 в 05:28
source

1 answer

1

You should bear in mind that making a select ->select(DB::raw('sum(monto) as sum')) will return a collection. for which you can not access to do validation if($sum_ == 0) , if only one table could participate in a more readable way using aggregates and return a value directly.

$sum= DB::table('eventos_tienen_trabajadores ')
        ->where('id_trabajador', '=', $id)
        ->where('estado', '=', '1')
        ->sum('monto');

if($sum==0) { ... }
  

As a recommendation, you should be careful when using raw-expressions   because you can leave a door open for SQL injection attacks

    
answered by 26.01.2018 / 05:52
source