From 845cc6cadcc6bf9166df5b5ae3113ee7a11eaad8 Mon Sep 17 00:00:00 2001 From: Brice1827 <61006271+Brice1827@users.noreply.github.com> Date: Fri, 5 Jul 2024 17:52:37 +0200 Subject: [PATCH] Update Model.php new function createMultiplePkNotId for tables where pk is not 'id' --- src/Models/Model.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/Models/Model.php b/src/Models/Model.php index 953754c..564cfcf 100644 --- a/src/Models/Model.php +++ b/src/Models/Model.php @@ -42,4 +42,40 @@ public static function createMultiple($modelClass, $multipleModels = []) return $models; } + + /** + * Creates and populates a set of models when table primary key is not "id". + * + * @param string $modelClass + * @param array $multipleModels + * @param string $pk + * @return array + */ + public static function createMultiplePkNotId($modelClass, $multipleModels = [], $pk = 'id') + { + $model = new $modelClass; + $formName = $model->formName(); + $post = Yii::$app->request->post($formName); + $models = []; + + if (!empty($multipleModels)) { + $keys = array_keys(ArrayHelper::map($multipleModels, $pk, $pk)); + $multipleModels = array_combine($keys, $multipleModels); + } + + if ($post && is_array($post)) { + foreach ($post as $i => $item) { + if (isset($item['id']) && !empty($item[$pk]) && isset($multipleModels[$item[$pk]])) { + $models[] = $multipleModels[$item[$pk]]; + } else { + $models[] = new $modelClass; + } + } + } + + unset($model, $formName, $post); + + return $models; + } + }