2016-11-16 59 views
5

我使用Laravel 5.3,並試圖返回一個搶劫與它的產品,只有最新訂單並與最新價格歷史只有最新的記錄。兩個連接都不返回任何內容,但如果我刪除$q->latest()->first();並用簡單的orderBy()替換它,我將獲得所有結果。我的查詢是:laravel查詢加入與

$data = $heist->with(['product'=> function($query) { 
    $query->with(['orders' => function($q) { 
    return $q->latest()->first(); 
    }]); 
    $query->with(['price_history' => function($q) { 
    return $q->latest()->first(); 
    }]); 
}])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get(); 
+0

你試過給'第一()''就像'' - > orderBy('active','DESC') - > first()'在結尾? – linuxartisan

+0

我試圖讓所有heists不只是第一個。我只想要最新的加入模型。 – Jongo

+0

那麼請重新格式化問題。它只說**最新_record _ ** – linuxartisan

回答

1

第一()調用是與調用取(1) - >得到()[0]; 這意味着限制返回到1並返回它。你想要的只是極限部分。所以如果你改變first()來取(1)。

更新

$data = $heist->with([ 
    'product'=> function($query) { 
     $query->with(
      [ 
       'orders' => function($q) { 
        $q->latest()->take(1); 
       }, 
       'price_history' => function($q) { 
        $q->latest()->take(1); 
       } 
      ] 
     ); 
    } 
])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get(); 
+0

這種方法可行,但只適用於結果中的第一次搶劫 -​​ 這與我以$ q-> latest() - > first()獲得的結果相似。第一個結果的價格歷史是空的,結果中的所有其他搶劫者都有訂單和價格歷史都是空的。 – Jongo

+0

@Jongo現在就試試這個。我相信你不需要返回關係規則,也不需要調用' - > get()'。如果你仍然得到相同的結果,你可以在查詢的最後調用' - > toSql()'而不是' - > get()',這樣我們可以進一步調查。 –

1

正如意見的討論,我相信這樣做的最簡單的方法是

$heists = $heist->with(['product'=> function($query) { 
    $query->with([ 
    'orders' => function($q) { 
     return $q->orderBy('created_at', 'desc')->take(1)->get(); 
    }, 
    'price_history' => function($q) { 
     return $q->orderBy('created_at', 'desc')->take(1)->get(); 
    } 
    ]); 
}])->orderBy('completed_at', 'desc')->orderBy('active', 'desc')->get(); 

希望這有助於:)

+0

與以下相同的問題 - 它適用於第一次搶劫結果(對於訂單而不是價格歷史記錄),但所有其他結果對於訂單和價格歷史都有空陣列 – Jongo

+0

結果如下所示:[{「id」:1,「 「orders_」:32594763262,「orders」:[{「id」:8827,「product_id」:32594763262,「created_at」:「2016-11-14 04:43:50」,「updated_at」:「2016-11-14 04:43:50「}],」price_history「:[]}, {」id「:2,」product_id「:32742307067,」orders「:[],」price_history「:[]}] – Jongo

+0

@Jongo If一行不存在於與該特定'product_id'相關的訂單表或price_history中,該集合顯然是空的。您是否試圖將任何產品的最新訂單和price_history放入收藏中? – prateekkathal