Skip to content

Commit

Permalink
Update Model.php
Browse files Browse the repository at this point in the history
new function createMultiplePkNotId for tables where pk is not 'id'
  • Loading branch information
Brice1827 authored Jul 5, 2024
1 parent a3ff955 commit 845cc6c
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}

0 comments on commit 845cc6c

Please sign in to comment.