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 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)