2014-10-16 74 views
0

我正在嘗試利用Laravels eagerlaoding功能,但它的行爲並不像預期的那樣。Laravel eagerloading無法正常工作

我嘗試過以下官方示例,但我無法重現它們的行爲。

我有一個Product類,其中hasMany('OrderLine')這個產品的實際訂單。

我想eagerload行顯示的產品和他們的訂單數的時候,所以我這樣做:

$products = Product::with('OrderLines')->get(); 
foreach($products as $product) { 
    var_dump($product->orderlines->first()); 
}; 

這應該做工精細,對不對?

好吧,當我檢查SQL日誌,出現這種情況:

[SQL] select * from "products" 
     bindings: [] 
     time: 0.71 milliseconds 
[SQL] select * from "order_lines" where "order_lines"."product_id" in (?, ?, ?, ?) 
     bindings: [2,3,4,5] 
     time: 0.79 milliseconds 
[SQL] select * from "order_lines" where "order_lines"."product_id" = ? 
     bindings: [2] 
     time: 0.32 milliseconds 
[SQL] select * from "order_lines" where "order_lines"."product_id" = ? 
     bindings: [3] 
     time: 0.3 milliseconds 
[SQL] select * from "order_lines" where "order_lines"."product_id" = ? 
     bindings: [4] 
     time: 0.31 milliseconds 
[SQL] select * from "order_lines" where "order_lines"."product_id" = ? 
     bindings: [5] 
     time: 0.29 milliseconds 

我似乎不能換我周圍爲什麼Laravel /雄辯的行爲這樣的頭。首先它正確地加載了這些行,但是當我循環產品時,它忽略了預加載的命令行......?

回答

1

您應該循環orderlines這樣:

foreach($products as $product) { 
    foreach ($product->orderlines as $ol) { 
    echo $ol->name; 
    } 
} 

編輯

我檢查了它,問題是字母的大小寫。

如果你們的關係有名字orderLines你應該使用:

$products = Product::with('orderLines')->get(); 

foreach($products as $product) { 
    foreach ($product->orderLines $ol) { 
    echo $ol->name; 
    } 
} 

所以在所有的地方,你應該使用orderLines完全相同的 - 沒有在一個地方OrderLines和其他orderlines

+0

不工作......循環運行良好,但日誌顯示與我的代碼中相同的N + 1查詢。 – 2014-10-16 20:50:42

+0

同樣的六個查詢,應該只是兩個查詢。 – 2014-10-16 20:53:25

+0

@NielsB。我已經更新了我的答案 – 2014-10-16 21:00:20