2016-07-26 63 views
0

我想從表order_status_history中的相關屬性的表訂單中獲取對象。從表order_status_history,我只需要狀態'審查'的最後一個記錄,所以我使用字段created_at排序asc。我的代碼到目前爲止,但我得到錯誤。Laravel whereHas eloqvent關係

$orders = Order::GetOrderHistoryReviewing()->get(); 

public function scopeGetOrderHistoryReviewing($query) 
    { 
     return $query->whereHas('statusHistory', function($q) { 

      $q->where('status', 'Reviewing')->orderBy('created_at','desc')->first(); 

     }); 
    } 

我需要從第二臺關係的一個對象

這是我的錯誤

[2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "orders" 
LINE 1: ...ries" where "order_status_histories"."order_id" = "orders"."... 
+1

那麼,什麼是你的問題?您提到了一個錯誤,但我在您的帖子中看不到任何錯誤。如果你需要幫助,你需要提供更多的信息,從你得到的錯誤的文本,你已經嘗試迄今修復它等。 – Styphon

+0

我認爲與第一isnt工作,我得到查詢錯誤 –

+0

偉大的,你還沒有告訴我們這個錯誤。複製錯誤給你的確切單詞,並用它們更新你的問題... – Styphon

回答

0

從你的問題,你顯然是想創建與狀態返回訂單範圍, '查看'並按降序對結果進行排序。

您需要從$q子查詢中刪除first()呼叫,並將orderBy移至$query的末尾。你的代碼應該看起來像。

public function scopeGetOrderHistoryReviewing($query) 
{ 
    return $query->whereHas('statusHistory', function($q) { 

     $q->where('status', 'Reviewing'); 

    })->orderBy('created_at','desc'); 
} 

然後,你可以這樣做:

$orders = Order::GetOrderHistoryReviewing()->get(); 
//OR to get the first record 
$first_order = Order::GetOrderHistoryReviewing()->first(); 
+0

但我需要第一條記錄從狀態歷史秩序通過desc不是表格訂單 –

+0

然後,您可以使用'orderBy('statusHistory.created_at','desc' )'而不是:) –

+0

但我不會得到第一個記錄 –