belongsTo('app\admin\model\app\physical\Goods', 'goods_id', 'id'); } public function skuPrices() { return $this->hasMany('app\admin\model\app\physical\SkuPrice', 'goods_id', 'goods_id'); } public static function getTree($goodsId) { $items = self::where('goods_id', $goodsId) ->where('uniacid', UNIACID) ->order('weigh', 'asc') ->select(); if (is_object($items) && method_exists($items, 'toArray')) { $items = $items->toArray(); } if (empty($items)) { return []; } // 确保所有项都是数组,并以ID为键 $data = []; foreach ($items as $item) { if (is_object($item)) { $item = $item->toArray(); } $item['children'] = []; $data[$item['id']] = $item; } $tree = []; foreach ($data as $key => $item) { if ($item['parent_id'] > 0 && isset($data[$item['parent_id']])) { $data[$item['parent_id']]['children'][] = &$data[$key]; } } foreach ($data as $key => $item) { if ($item['parent_id'] == 0) { $tree[] = $data[$key]; } } return $tree; } }