0

So, I have been creating migrations using Phinx. I want to be able to truncate all the tables(148 tables) before running the seed files. I am thinking about just creating a seed file that will be ran first and then it will truncate all the tables. The catch is that I don't want to have to ever change this file if we add more tables. How would I go about doing this. Maybe doing a Show tables and then looping through them, but not exactly sure how to do that. Any help would be great! This is what I have so far.

<?php
use Phinx\Seed\AbstractSeed;
class BonusRuleTypesSeeder extends AbstractSeed
{
    public function run()
    {
        $this->execute('SET foreign_key_checks=0');
        // some code here
        $this->execute('SET foreign_key_checks=1');
    }
}
hjcoder18
  • 449
  • 1
  • 5
  • 13

2 Answers2

2

If you have a migrations table, then this will truncate that table as well. This would work.

 $this->execute('SET foreign_key_checks=0');   
        foreach($tables as $table){
            $table = $table["Tables_in_".$database];
            if ($table != $config->getProperty(['phinx', 'default_migration_table'])){
                $sql = "TRUNCATE TABLE ".$table;
                $this->execute($sql);
            }
        }
Hunter Marshall
  • 201
  • 4
  • 12
0

Here is the answer

$config = new Config(__DIR__.'/../../config/default.ini',true);
        $host = $config->getProperty(['db', 'host']);
        $database = $config->getProperty(['db', 'name']);
        $username = $config->getProperty(['db', 'username']);
        $password = $config->getProperty(['db', 'password']);

        $mysqli = new mysqli($host, $username, $password, $database);
        $query = "Show tables";
        $tables = $mysqli->query($query);
        $tables->fetch_all();
        $mysqli->close();

        $this->execute('SET foreign_key_checks=0');   
        foreach($tables as $table){
            $table = $table["Tables_in_".$database];
            $sql = "TRUNCATE TABLE ".$table;
            $this->execute($sql);
        }
        $this->execute('SET foreign_key_checks=1');
hjcoder18
  • 449
  • 1
  • 5
  • 13