2016-04-07 9 views
0

Ich möchte diese Abfrage in Laravel schreiben 5,2Laravel subquery

SELECT b.id, 
     TotalP, 
     b.booking_amount 
FROM booking b 
LEFT JOIN 
    (SELECT sum(amount) AS TotalP, 
      booking_id 
    FROM payment 
    GROUP BY booking_id) AS T ON b.id = T.booking_id 
WHERE COALESCE(TotalP, 0) < b.booking_amount 

Meine Frage zu diesem Beitrag in Zusammenhang steht. Ich schrieb eine Abfrage nach der Suche und Studium, aber es funktioniert nicht, und mehr Zwang

$result = DB::table('my_booking') 
     ->select('booking_name') 
     ->leftJoin(DB::raw('(SELECT booking_id,sum(amount) as TotalP FROM `my_payment` GROUP BY booking_id) TotalPayment'), function($join) 
     { 
      $join->on('my_booking.id', '=', 'TotalPayment.booking_id'); 
     }) 
     ->get(); 

Sql query to get data diffrence of total in 2 tables

Antwort

1

benötigen Sie können dies versuchen,

$booking_payments = Booking::with('Payment')->find(1); 

$total = 0; 
foreach($booking_payments->payment as $booking_payment){ 
$total += $booking_payment->amount; 
} 

if($booking_payments->booking_amount == $total){ 
// if the total and booking_amount is equal 
} 
1

Dies sollte in Laravel arbeiten, und Sie geben das gleiche genaue Ergebnis wie Ihre MySQL-Abfrage. Ich habe COALESCE in den Auswahlbereich der Unterabfrage verschoben, so dass Sie keine rohe DB where-Anweisung in Laravel schreiben müssen.

$sql_subquery = "(SELECT COALESCE(SUM(amount),0) AS TotalP, 
          booking_id 
        FROM payment 
        GROUP BY booking_id) AS T"; 


$result = DB::table('booking AS b') 
      ->leftJoin(DB::raw($sql_subquery), 'b.id', '=', 'T.booking_id') 
      ->where('T.TotalP','<', 'b.booking_amount') 
      ->select('b.id','T.TotalP','b.booking_amount') 
      ->get();