/** * @param array $dictionary * @param array $data * @param array $existing * @param mixed $parentId */ protected function buildRebuildDictionary(array &$dictionary, array $data, array &$existing, $parentId = null) { $keyName = $this->model->getKeyName(); foreach ($data as $itemData) { if (!isset($itemData[$keyName])) { $model = $this->model->newInstance(); // We will save it as raw node since tree will be fixed $model->rawNode(0, 0, $parentId); } else { if (!isset($existing[$key = $itemData[$keyName]])) { throw new ModelNotFoundException(); } $model = $existing[$key]; unset($existing[$key]); } $model->fill(Arr::except($itemData, 'children'))->save(); $dictionary[$parentId][] = $model; if (!isset($itemData['children'])) { continue; } $this->buildRebuildDictionary($dictionary, $itemData['children'], $existing, $model->getKey()); } }