For the complete documentation index, see llms.txt. This page is also available as Markdown.

Table Command

This TableCommand class provides methods to synchronize database tables by creating, updating, and modifying schema definitions in MySQL.

handle() - Execute Table Synchronization

public function handle($tableName) {
    $modelClass = "\\App\\Models\\".ucfirst($tableName).'Model';
    
    // Initialize the model
    $model = new $modelClass();
    $table = $model->_table();
    $schema = $model->_schema();
    
    // Check the table and synchronize its structure
    $this->syncTableSchema($table, $schema);

    echo "{$table} Table has been synchronized.\n";
}
  • Dynamically creates a model class using the given $tableName.

  • Calls _table() and _schema() methods from the model to retrieve table name and schema definition.

  • Passes these values to syncTableSchema() for synchronization.

syncTableSchema() - Synchronize Table Schema

  • Checks if the table exists using tableExists().

  • If the table does not exist, calls createTable().

  • Otherwise, calls updateTable() to modify the schema.

tableExists() - Check If Table Exists

  • Executes a SQL query to check if a table exists in the database.

  • Returns true if the table exists, otherwise false.

createTable() - Create a New Table

  • Loops through the schema and builds SQL column definitions.

  • Constructs a CREATE TABLE SQL statement using utf8mb4 charset.

  • Executes the query to create the table in MySQL.

updateTable() - Update Table Schema

  • Retrieves the current column list of the table.

  • If a column does not exist, calls addColumn().

  • If a column needs modification, calls modifyColumn().

getCurrentColumns() - Get Current Table Columns

  • Executes the SHOW COLUMNS SQL command to retrieve all columns in a table.

Example:

If you want to create a new Table and named as 'user',mMake sure you have the UserModel.php file in the application/Models directory with the following content:

Then run the following command:

And the result:

Last updated

Was this helpful?