dou4624 2014-10-16 20:34
浏览 45
已采纳

Laravel渴望加载不工作

I am trying to utilize Laravels eagerlaoding functionality, but it doesn't at all behave like expected.

I've tried following the official examples, but I cannot reproduce their behavior.

I have a Product class which hasMany('OrderLine') meaning actual orders for this product.

I'd like to eagerload the lines, when displaying the products and their orders count, so I do this:

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

This should work fine, right?

Well, when I check the SQL log, this happens:

[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

I can't seem to wrap my head around why Laravel/Eloquent behaves this way. First it correctly eagerloads the lines, but then it ignores the preloaded orderlines when I loop over the products...?

  • 写回答

1条回答 默认 最新

  • douyazi1129 2014-10-16 20:47
    关注

    You should loop orderlines this way:

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

    EDIT

    I've checked it and the problem is case of letters.

    If your relation has name orderLines you should use:

    $products = Product::with('orderLines')->get();
    
    foreach($products as $product) {
      foreach ($product->orderLines $ol) {
        echo $ol->name;
      }
    }
    

    so in all places you should use orderLines exactly the same - not in one place OrderLines and in the other orderlines

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题