Question about use "Migrations" (Need Help)


#1

Hi

Correct me if I’m wrong:

Migrations plugin - allows you to change tables in the database, but you need to know in advance and specify, for example: what columns will be called in the database.
If I do not know in advance how they should be named, I can not dynamically name and create columns in table database.

For example, in my case:
Using data from a third-party API, I need to select the column name and data for these columns from the received JSON, but for my purposes, this plugin is not suitable. I’m right?

If I’m right, can you tell me how to solve this problem?

Or can i do something like this or not?:

<?php
use Migrations\AbstractMigration;
class AdminsController extends AbstractMigration
{
    public function change($array_res_api) // array with data from the controller action
    {
        $table = $this->table('metrica');

        foreach($array_res_api as $key => $value){
            $table->addColumn($key, 'string', [
               'value' => $value,
               'limit' => 100,
               'null' => false,
            ]);
        }

        $table->create();
    }
}

Thank you in advance for your cooperation :slight_smile:


#2

To my regret, no one answered my question, so I did not have to use the migration plugin in this case :frowning:.
If someone needs something like this, then I did this:

foreach($metrics as $key => $value){
   // We get data on all the columns of the table existing in the table
   $arr_col= $connection->execute(
     'pragma table_info(metrica)'
   )->fetchAll('assoc');

   $found = false;

  // Whether we look at all at us in the table metrica such column (string)$value[0]
    foreach($arr_col as $int => $val){
        if (in_array((string)$value[0], $val)) {
           $found = true; // Column found
           break; // Stop the cycle
       }
    }

   // We check whether the column was found, and if not, we will add such a column to the database
   if (!$found){
         $connection->execute(
            'ALTER TABLE metrica ADD COLUMN `'.(string)$value[0].'` INTEGER'
         );
    }

   // Insert the data into the table (string)$value[0]
   $connection->execute(
      'INSERT INTO metrica (`date`, "'.(string)$value[0].'") VALUES ("'.$ga_date.'", '.(int)$value[1].')'
   );
}