doutouman6245 2017-03-08 13:00
浏览 80
已采纳

当json在Laravel中编码嵌套关系时的性能问题

I'm fetching data from a database using Laravel's (5.2) Eloquent ORM like so:

$orders = Order::with([
    'customer',
    'items',
    'items.product',
    'items.product.shop' => function ($query) {
        $query->select(['id', 'title']);
    }
])->get();

Note: the reason why an order is not tied to a single shop is that orders may contain items from multiple shops. Each item references the ordered product, which in turn has a reference to the shop it belongs to.

This works fine, however, when I want to return the result to a view and render it there, it takes a long time to json_encode it.

I confirmed that json_encode is indeed the bottleneck, if I just execute the query and immediately die afterwards, the response is almost instant. However, if I do a $orders->toJson() (or json_encode($orders)) after the query, I experience the same delay in response as with returning the result to the view.

Apparently the problem lies in the (too deeply?) nested property of items.product.shop, if I remove that, the call to json_encode doesn't induce any performance issues.

Here's a sample output of a single order:

{
  "id": 71,
  "total_sum": "5.88",
  "customer": {
    "id": 68,
    "first_name": "One Large",
    "last_name": "Men's"
  },
  "items": [
    {
      "id": 105,
      "quantity": "1",
      "price_single": "1.2",
      "price_total": "1.2",
      "color_id": "6",
      "size_id": "5",
      "order_id": "71",
      "product": {
        "id": 149,
        "name": "Men's",
        "shop": {
          "id": 109,
          "title": "general test"
        }
      }
    }
  ]
}
  • 写回答

1条回答 默认 最新

  • dsrw29618 2017-03-08 13:51
    关注

    Found the culprit, I have an additional attribute in my shop model (added via $appends) that gets calculated by using a nested for-loop.

    Apparently still fast enough when working directly on shops, but since in the above example each order has several items and each item references a shop, performance degrades.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog