2016-08-19 56 views
1

爲了使我需要編寫連接查詢的報表。我現在在sql中編寫了連接查詢,我需要在laravel 5.2中編寫相同的查詢。 我的SQL查詢如下。如何在laravel 5.2中編寫sql連接查詢

SELECT a.accountID, a.deviceID, b.description, a.timestamp, a.latitude, a.longitude, a.speedKPH as speed, a.heading, a.altitude, a.address, a.distanceKM as distance, a.odometerKM as odometer, a.IbatVolts, a.EbatVolts, a.ITempr, a.fuelLevel, a.inputState, a.IgnRuntime, a.GPSFixType, a.GPSPDOP, a.AlertType, a.speedLimitKPH, a.isTollRoad 
FROM eventdata as a, device as b 
WHERE a.deviceID = '$deviceID' 
    AND a.accountID = '$accountID' 
    AND a.timestamp >= $dt1 
    AND a.timestamp <= $dt2 
    AND a.deviceID=b.deviceID 
ORDER BY timestamp DESC 

我試圖寫在laravel也。查詢如下

DB::table('device as b') 
    ->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID') 
    ->where('a.deviceID', '=', '$deviceID') 
    ->where('a.accountID', '=', '$accountID') 
    ->where('a.timestamp', '>=', '$dt1') 
    ->where('a.timestamp', '<=', '$dt2') 
    ->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp', 
      'a.latitude', 'a.longitude', 'a.speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.AlterType', 'a.speedLimitKPH', 'a.isTollRoad')->get(): 

是這樣嗎?任何人都可以告訴我,並幫助我寫出正確的查詢。

+0

你laravel代碼將執行內部聯接,但是,你寫的查詢使用交叉連接..您是否獲得任何意外的結果當你嘗試它? ([參考文檔](https://laravel.com/docs/5.2/queries#joins)) – Terminus

+0

nop ..其工作完美..但我需要知道,這是足夠的發展? –

回答

3

聯接語法在laravel 5.2:

$users = DB::table('users') 
      ->join('contacts', 'users.id', '=', 'contacts.user_id') 
      ->join('orders', 'users.id', '=', 'orders.user_id') 
      ->select('users.*', 'contacts.phone', 'orders.price') 
      ->get(); 

和你使用的是相同的。如果你正面臨的任何問題,而不僅僅是通過使用打印原始SQL查詢:

DB::enableQueryLog(); 

// Your query 

$queries = DB::getQueryLog(); 
print_r($queries); // it will print raw sql query in prepared statement style 
+0

好的,謝謝...... –

相關問題