From 87c9c991f471b5bd9331fb26f014427750b898ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Sat, 17 Jun 2023 11:53:46 +0200 Subject: [PATCH] implement multi relation loading --- src/PersistentData/Model/Model.php | 2 ++ src/PersistentData/PersistentDataManager.php | 34 ++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/PersistentData/Model/Model.php b/src/PersistentData/Model/Model.php index c5f566c..9c100ae 100644 --- a/src/PersistentData/Model/Model.php +++ b/src/PersistentData/Model/Model.php @@ -8,6 +8,8 @@ abstract class Model protected static array $relations = []; + protected static array $multiRelations = []; + protected $id = null; private array $snapshot = []; diff --git a/src/PersistentData/PersistentDataManager.php b/src/PersistentData/PersistentDataManager.php index 6547782..f0a2569 100644 --- a/src/PersistentData/PersistentDataManager.php +++ b/src/PersistentData/PersistentDataManager.php @@ -92,6 +92,40 @@ class PersistentDataManager implements IPersistentDataManager } } + public function loadMultiRelationsFromDb(array $models, string $relation, bool $useRelations = false, array $withRelations = []) { + if (count($models) === 0) { + return; + } + + $parentModelType = get_class($models[0]); + $relationModelsSetter = 'set' . str_replace('_', '', ucwords($relation, '_')); + $relationModelType = $parentModelType::$multiRelations[$relation][0]; + $reverseRelation = $parentModelType::$multiRelations[$relation][1]; + $reverseRelationIdGetter = 'get' . str_replace('_', '', ucwords($reverseRelation, '_')) . 'Id'; + + $parentModelsById = []; + foreach ($models as $model) { + $parentModelsById[$model->getId()] = $model; + } + + $select = new Select($this->dbConnection); + $select->where($reverseRelation . '_id', 'IN', array_keys($parentModelsById)); + + $relationsByParentModelId = []; + foreach ($this->selectMultipleFromDb($select, $relationModelType, $useRelations, $withRelations) as $relationModel) { + $reverseRelationId = $relationModel->$reverseRelationIdGetter(); + if (!isset($relationsByParentModelId[$reverseRelationId])) { + $relationsByParentModelId[$reverseRelationId] = []; + } + $relationsByParentModelId[$reverseRelationId][] = $relationModel; + } + + foreach ($parentModelsById as $parentModelId => $parentModel) { + $relationModels = $relationsByParentModelId[$parentModelId] ?? []; + $parentModel->$relationModelsSetter($relationModels); + } + } + public function saveToDb(Model $model): void { $this->syncRelations($model);