Help me find a mistake in migration yii2



  • There's a code like this:

    class m160115_201537_insert_data_in_phrases extends Migration
    {
        public function exists($table_name, $fields)
        {
            $query = new \yii\db\Query();
            $model = $query
                ->select(["*"])
                ->from($this->db->getTableSchema($table_name)->name)
                ->where($fields)
                ->exists();
    
        return $model;
    }
    
    public function save($table_name, $fields, $exists = null)
    {
        if (is_null($exists)) {
            $exists = $fields;
        }
    
        if ($this->exists($table_name, $exists)) {
            $this->update($table_name, $fields);
        } else {
            $this->insert($table_name, $fields);
        }
    }
    
    public function up()
    {
        $phrases_array = require Yii::getAlias('@t10s/phrases.php');
    
        var_dump($phrases_array);
    
        foreach ($phrases_array as $name => $array) {
            if (count($array) != 3) {
                Console::say("Не все переводы для поля %s были добавлены! Пожалуйста, добавь все переводы!", [$name]);
                return false;
            }
            $this->save('{{%phrases}}', [
                'name' => $name,
                'locale' => 'ru',
                'text' => htmlspecialchars($array[0]),
            ], [
                'name' => $name,
                'locale' => 'ru',
            ]);
            echo $name;
        }
    }
    
    public function down()
    {
        echo "Для того, чтоб применить новые переводы просто запустите миграцию еще раз\n";
        return true;
    }
    

    }

    When there's no field in the database, everything's fine. When I want to change the translation of some field, it makes a mistake:

    UXIBA: The repetitive key violates the limit of uniqueness

    If the limitation of uniqueness is removed, the base will be filled with the same values from the first element of the mass, as many elements.

    Why is this happening? How do you do that? How can that be easier?



  • I think you have too much manipulation to do something like this, in principle.

    If it doesn't work as it is now, you can use the standard OBD thing: ON DUPLICATE KEY UPDATE

    ON DUPLICATE KEY UPDATE - If you indicate ON DUPLICATE KEY UPDATE (news MySQL 4.1.0and a row is inserted which causes a mistake of overlapping primary (PRIMARY) or a unique (UNIQUE) key, UPDATE of the old row.

    With help createCommand This is done:

    Yii::$app->db->createCommand('INSERT INTO {{%table}} (field1, field2) VALUES ("value1", "value2") ON DUPLICATE KEY UPDATE field1 = VALUES (field1);')->execute();

    Where after ON DUPLICATE KEY UPDATE You can ask for any field and any number that you need to rewrite.


    Useable batchInsert (method for baggage) proposed by the Freimvork itself (data package) http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert%28%29-detail with the same parameter ON DUPLICATE KEY UPDATE

    $db = Yii::$app->db;
    $sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
    $db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();
    

    Where? $table - Table, $fields - the names of the fields, $rows - data set


    And another way to manipulate the model. Maybe it's not exactly corroque and it's staining some underwater rocks, but you can keep it in your head.

    Example (Don't forget to connect) namespace Model:

    use yii\db\Schema;
    use yii\db\Migration;
    use common\models\Test;
    

    class m160118_064910_test extends Migration {

    public function up() {
        $user = Test::find()
            ->where(['field1' => 'value1'])
            ->one();
    
        if(!$user){
            $user = new User;
        }
    
        $user->attributes=array(
            'field1' => 'value1',
            'field2' => 'text 111',
        );
    
        $res = $user->save();
    }
    
    public function down() {
        // some migration here      
    }
    

    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2