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 /雄辩的行为这样的头。首先它正确地加载了这些行,但是当我循环产品时,它忽略了预加载的命令行......?
不工作......循环运行良好,但日志显示与我的代码中相同的N + 1查询。 – 2014-10-16 20:50:42
同样的六个查询,应该只是两个查询。 – 2014-10-16 20:53:25
@NielsB。我已经更新了我的答案 – 2014-10-16 21:00:20