Home > Software design >  How to write this sql with laravel?
How to write this sql with laravel?

Time:08-28

    select count('vehicules.id')
    from vehicules
      INNER JOIN (equipements, contenirs)
         ON (contenirs.vehicule_id = vehicules.id AND contenirs.equipement_id = equipements.id)
     WHERE(vehicules.KMActuel-contenirs.dernierKM > equipements.kilometrageMax);

That is the code that I want to execute with laravel. I tried code like :

$special = DB::select("SELECT COUNT('vehicules.id') FROM vehicules INNER JOIN (equipements, contenirs) ON (contenirs.vehicule_id = vehicules.id AND contenirs.equipement_id = equipements.id) WHERE(vehicules.KMActuel-contenirs.dernierKM > equipements.kilometrageMax)");

I call the variable in my view and i get an error like:

htmlspecialchars() expects parameter 1 to be string, array given (View: C:\laragon\www\GSMV\resources\views\dash.blade.php) 

CodePudding user response:

You can't execute expressions in a string you pass to regular eloquent methods. You have to use raw expressions that can be parsed accordingly:

DB::table('vehicules')
    ->join('contenirs', 'vehicules.id', 'contenirs.vehicule_id') 
    ->join('equipements','equipements.id','contenirs.equipement_id') 
    ->whereRaw('vehicules.KMActuel-contenirs.dernierKM > equipements.kilometrageMax')
    ->select('vehicules.*', 'contenirs.designation')
    ->count('vehicules.id');
  • Related