在开发过程中,我们经常遇到一对多的场景,
例如:查询订单列表,并且展示订单详情商品、数量数据
思路0:传统做法
a. 查询订单列表
b. 遍历订单详情 $orderList = select from order where xx; foreach($orderList as $orderItem) { $orderItem->detailList = select from order_detail where order_id = $orderItem->id; }分析:查询SQL次数为:N+1(N为订单个数),这样频繁请求数据库,影响效率
优化:减少频繁请求数据库
思路1:
a. 查询订单列表后,利用in查出所有订单详情
b. 通过(订单表id => 订单详情表order_id)遍历匹配数据 $orderList = select from order where xx; $orderId = array_pluck($orderList, ‘id’); // Laravel内置数组辅助函数 $orderDetailList = select from order_detail where order_id IN $orderId; foreach($orderList as $orderItem) { $detailListTemp = []; foreach($orderDetailList as $orderDetailItem) { if ($orderItem->id == $orderDetailItem->order_id) { $detailListTemp[] = $orderDetailItem; } } $orderItem->detailList = $detailListTemp;分析:降低查询后,但2层遍历,复杂度较高,数量过大容易内存溢出
优化:降低复杂度
思路2:
a. 查询订单列表后,利用in查出所有订单详情
b. 订单详情列表转换成以订单ID为索引,用isset来匹配订单的详情 $orderList = select from order where xx; $orderId = array_pluck($orderList, ‘id’); // Laravel内置数组辅助函数 $orderDetailList = select from order_detail where order_id IN $orderId;
// 将订单详情转换成以订单ID为索引【方式1】$orderDetailList = arrayGroup($orderDetailList, 'order_id');// 或:将订单详情转换成以订单ID为索引【方式2:如果为一对一,可以用array_column】// $orderList = array_column($orderDetailList, null, 'order_id');foreach($orderList as $orderItem) {$orderItem->detailList = $orderDetailList[$orderItem->id] ?? [];}// 根据KEY数组分组function arrayGroup($list, $key) {$newList = [];foreach ($list as $item) {$newList[$item[$key]][] = $item;}return $newList;
相关推荐
© 2020 asciim码
人生就是一场修行