2017-01-09 49 views
0

卡住了。 我使用這個沒有編號的查詢來獲取所有這些數據。Laravel使用編號order_details查詢訂單

$orders = $this->order 
    ->with('orderDetails', 'orderDetails.product') 
    ->today() 
    ->get(); 

關係

訂單:

public function orderDetails(){ 
    return $this->hasMany('App\OrderDetail', 'order_id'); 
} 

的OrderDetail:

public function order() 
{ 
    return $this->belongsTo('App\Order', 'order_id', 'id'); 
} 

public function product() 
{ 
    return $this->belongsTo('App\Product', 'id_products', 'id'); 
} 

但試圖用同樣的東西來獲得數據以特定的順序不返回ORDER_DETAILS 。

public function invoice(Request $request, $id) 
    { 
    $ordered = $this->order 
     ->find($id) 
     ->with('orderDetails', 'orderDetails.product'); 

    return response()->json($ordered); 
    } 

爲什麼傳遞id時它的行爲不同?

回答

1

當您使用find查詢在其他指令之前執行。您需要使用where

$ordered = $this->order 
    ->where('order_id', $id) 
    ->with('orderDetails', 'orderDetails.product') 
    ->get(); 
+0

正是我需要的!謝謝 –

1

嘗試只使用這種方式:

$ordered = $this->order->find($id); 

return response()->json($ordered); 

的laravel已經轉向了基於您在模型中輸入任何映射關係。 在這種情況下,你在你的反應ORDERDETAILS看起來就像這樣:

訂單:{ ID: 「1」, Xpto: 「無所謂」, 訂單明細:{ ID: 「1」 } }

+0

我已經試過這種方式了,它沒有附帶orderDetails。只返回該訂單。 –