2015-05-28 21 views

risposta

12

Mentre Laravel non fornisce alcun metodo per verificare l'esistenza di una chiave, è possibile utilizzare qualsiasi of the available queries in MySQL e quindi utilizzare DB::select().

Per esempio:

$keyExists = DB::select(
    DB::raw(
     'SHOW KEYS 
     FROM your_table_name 
     WHERE Key_name=\'your_key_name\'' 
    ) 
); 

Basta sostituire your_table_name e your_key_name per i valori corretti.

+7

laravel utilizza Doctrine in punti (in particolare schema), in modo da 'doctrine/di dbal'' listTableIndexes() 'potrebbe essere una soluzione migliore di una chiamata 'DB :: raw' che è specifica per MySQL. http://doctrine-dbal.readthedocs.org/en/latest/reference/schema-manager.html – ceejayoz

+2

@ceejayoz Grazie per quello. Ho imparato qualcosa oggi :) –

+4

@ceejayoz Per ottenere Doctrine Manager in Laravel: '$ conn = Schema :: getConnection() -> getDoctrineSchemaManager()' – shrimpwagon

5

Se si utilizza Laravel, molto probabilmente si avrà accesso a un ORM come Eloquent. Supponendo che si sta utilizzando Eloquente, si potrebbe essere in grado di fare qualcosa del genere:

try { 
    Schema::table(
     'the_name_of_your_table', 
     function (Blueprint $table) { 
      $sm = Schema::getConnection()->getDoctrineSchemaManager(); 
      $indexesFound = $sm->listTableIndexes('the_name_of_your_table'); 

      $indexesToCheck = [ 
       'index_name_1', 
       'index_name_2', 
       'index_name_3', 
       'index_name_4' 
      ]; 

      foreach ($indexesToCheck as $currentIndex) { 
       if (array_key_exists($currentIndex, $indexesFound)) { 
        // The current index exists in the table, do something here :) 
       } 
      } 
     } 
    ); 
} catch (Exception $e) { 

} 
Problemi correlati