Answer the question
In order to leave comments, you need to log in
How to reset Yii2 model?
Actually there is such a code
<?php
namespace console\controllers;
use yii\console\Controller;
use common\models\Settings;
use Yii;
class SettingsController extends Controller {
public function actionInit() {
$settings = Yii::$app->params['settings'];
foreach ($settings as $key => $param) {
if(Settings::find(['key' => $key])->one() === NULL) {
$obj = new Settings;
$obj->key = $key;
$obj->type = $param[0];
$obj->value = $param[1];
if($obj->validate()) {
$obj->save();
} else {
print 'Error on ' . $key . '\n' . $obj->errors;
}
unset($obj);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Solved my problem myself, use exists()Settings::find()->where(['key' => $key])->exists()
You are tough)) As a rule, requests in a loop are not the best idea (there are exceptions, of course, but this is not the case).
I recommend that you first make a selection of available settings by keys, then insert the difference with a batch.
If in params['settings'] someone mistakenly sets 'key' => 'value', your system will not work correctly.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question