如何在Laravel中的控制器内部编写普通的SQL查询

时间:2019-06-11 10:29:47

标签: mysql laravel

我想知道如何在laravel控制器中写下普通的sql查询吗?

SELECT 

       vd.photo,
       CONCAT(vd.firstName," ",vd.lastName) as FullName,
       v.photo,
       v.vehicleModel,
       sr.tripType,
       sr.schoolTime,
       GROUP_CONCAT( rs.schoolName SEPARATOR ' ') as School_Name,
       GROUP_CONCAT( cp.checkPoint SEPARATOR ' ') as CheckPoints

FROM 

     vehicles v,
     school_van_routes sr,
     routes_schools rs,
     school_route_check_points cp,
     van_drivers vd,
     van_owners vo

WHERE

      v.numberPlate=sr.selectVehicle 
      AND sr.id=rs.routeId 
      AND sr.id= cp.routeId
      AND v.vanOwnerEmail=vo.email 
      AND vo.email =vd.email

GROUP BY v.id

2 个答案:

答案 0 :(得分:3)

欢迎使用StackOverflow。

如果您要执行原始SQL而不是使用查询生成器,则可以尝试:

$results = DB::select("SELECT * ..")

更多内容:https://laravel.com/docs/5.8/database#running-queries

答案 1 :(得分:0)

这是转换SQL查询的方法。

$result = DB::table(DB::raw('vehicles v, school_van_routes sr, routes_schools rs, school_route_check_points cp, van_drivers vd, van_owners vo')) 
        ->select(DB::raw("vd.photo, CONCAT(vd.firstName,' ',vd.lastName) as FullName, v.photo, v.vehicleModel, sr.tripType, sr.schoolTime, GROUP_CONCAT( rs.schoolName SEPARATOR ' ') as School_Name, GROUP_CONCAT( cp.checkPoint SEPARATOR ' ') as CheckPoints"))
        ->whereRaw('v.numberPlate=sr.selectVehicle')
        ->whereRaw('sr.id=rs.routeId')
        ->whereRaw('sr.id= cp.routeId')
        ->whereRaw('v.vanOwnerEmail=vo.email')
        ->whereRaw('vo.email =vd.email')
        ->groupBy('v.id', 'v.photo', 'vd.photo', 'v.vehicleModel', 'sr.tripType', 'sr.schoolTime')
        ->get();

dd($result);