0
0
0ct0g3n2015-02-14 17:55:37
Yii
0ct0g3n, 2015-02-14 17:55:37

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

It brings the parameters from the file into the database through the model.
The foreach itself passes through the parameters normally, and the first parameter is successfully entered into the database, but the following calls to Settings::find return the same object, so subsequent parameters are no longer entered into the database.
How to deal with it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0ct0g3n, 2015-02-14
@0ct0g3n

Solved my problem myself, use exists()
Settings::find()->where(['key' => $key])->exists()

I
index0h, 2015-02-15
@index0h

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 question

Ask a Question

731 491 924 answers to any question