Skip to content

Commit

Permalink
Update Model.php
Browse files Browse the repository at this point in the history
createLMultiple with an optional paramter pk
  • Loading branch information
Brice1827 authored Jul 8, 2024
1 parent 81b36ee commit 7f67625
Showing 1 changed file with 2 additions and 37 deletions.
39 changes: 2 additions & 37 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,44 +14,10 @@ class Model extends \yii\base\Model
*
* @param string $modelClass
* @param array $multipleModels
* @return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];

if (!empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}

if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}

unset($model, $formName, $post);

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')
public static function createMultiple($modelClass, $multipleModels = [], $pk = 'id')
{
$model = new $modelClass;
$formName = $model->formName();
Expand All @@ -65,7 +31,7 @@ public static function createMultiplePkNotId($modelClass, $multipleModels = [],

if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item[$pk]) && isset($multipleModels[$item[$pk]])) {
if (isset($item[$pk]) && !empty($item[$pk]) && isset($multipleModels[$item[$pk]])) {
$models[] = $multipleModels[$item[$pk]];
} else {
$models[] = new $modelClass;
Expand All @@ -77,5 +43,4 @@ public static function createMultiplePkNotId($modelClass, $multipleModels = [],

return $models;
}

}

0 comments on commit 7f67625

Please sign in to comment.