2016-08-19 3 views
1

レポートを作成するには、結合クエリを書く必要があります。私は今SQLで結合クエリを書いた、私はlaravel 5.2で同じクエリを記述する必要があります。 私のSQLクエリは以下の通りです。laravelでsql join queryを書く方法5.2

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コードは、あなたが書いたクエリはクロス結合を使用、内部結合を実行しますが..あなたは、任意の予期しない結果を得ている:場合は、あなたが使用して生のSQLクエリを印刷することができますよりも、すべての問題に直面していますあなたがそれを試すとき? ([ドキュメントへの参照](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(); 

、あなたはそれを用いています。

DB::enableQueryLog(); 

// Your query 

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

ok ..ありがとう...... –