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; + } + }