title: To clean/fill table after table in the correct order, can I simply sort all tables based on FKs?
body: <p>This is more like a conceptual question.</p>
  
  <p>I have a scheduled task with many input tables (SQLite) <code>table1 ... tableN</code> and I need to perform a series of delete/insert into MySQL, processing table after table. </p>
  
  <pre><code>READ SQLITE TABLE -&gt; EMPTY MYSQL TABLE -&gt; FILL MYSQL TABLE
  </code></pre>
  
  <p>Of course if (MySQL) <code>table1</code> has a foreign key poiting to <code>table2</code>, <code>table2</code> should be deleted and filled <em>before</em> <code>table1</code>. I manually sort the incoming tables, but it's not a good idea with 30+ table and can lead to errors.</p>
  
  <p><code>SET FOREIGN_KEY_CHECKS = 0</code> is <strong>not an option</strong>.</p>
  
  <p>So problem would be sorting all MySQL table based on the number of incoming FKs (high to low), like:</p>
  
  <pre><code>// Doctrine DBAL example but it's easily understandable
  $schema = $this-&gt;connection-&gt;getSchemaManager();
  
  // Init chart where keys are table names, values are # of incoming FKs
  $chart = array_fill_keys($schema-&gt;listTableNames(), 0);
  
  // Build the chart
  foreach ($schema-&gt;listTables() as $table) {
      foreach ($table-&gt;getForeignKeys() as $foreignKey) {
          $chart[$foreignKey-&gt;getForeignTableName()]++;
      }
  }
  
  // Sort high to low by values
  arsort($chart);
  </code></pre>
  
  <p>Are there flaws in my reasoning? My question is <strong>how to deal with self-foreign keys</strong> (simply ignore it?) and how to <strong>deal with circular references</strong> (i.e. <code>table1 -&gt; table2 -&gt; table3 -&gt; table1</code>).</p>