How to add new tables to an existing database¶
In the terminal, go to your project directory. Then to create the a table type:
php artisan make:migration create_tableName_table
In your database/migrations directory you will now find a .php
file with the name you gave it.
Go into this file, and in the up()
function create your table:
Schema::create('job', function(Blueprint $table{
$table->increments('id'); //appears automatically
/*Your columns go in here*/
$table->integer('Submitter_id')->unsigned();
$table->string('RScript_name');
$table->string('arguments');
$table->enum('Status', ['waiting', 'running', 'cancelled', 'completed', 'failed']); //enum allows for specific strings to be given
$table->timestamps(); //appears automatically
});
There will also be an auto-generated down()
function, which will remove the table.
Leave this alone.
Make as many tables as you need, using the command line for each.
Once the tables have been made you can create foreign keys.
This requires another .php
script.
In the terminal write the command:
php artisan make:migration add_foreign_keys_for_tableNames
Inside this script you will once again have up()
and down()
functions.
In the up function you add the foreign keys:
Schema::disableForeignKeyConstraints();
Schema::table('job'/*table name*/, function(Blueprint $table){
$table->foreign('Submitter_id'/*column name in table*/)
->references->('id'/*column name on other table*/)
->on('users'/*other table*/)
->onDelete('cascade')
->onUpdate('cascade');
});
Add as many foreign keys as you need, following this format.
Each key in the same table can be added inside the same Schema, just add another: $table->foreign('columnName' ...);
.
Once you've added all the foreign keys you want to the first table you can move on to the next table by creating a new schema, following the format above.
Once you're finished adding foreign keys make sure you re-enable the foreign key constraints inside the up()
function
Schema::enableForeignKeyConstraints();
Then go to the down()
function.
Unlike when creating tables, this is not automatically filled in, you have to do it yourself.
Schema::table('job' /*table name*/, function(Blueprint, $table){
$table->dropForeign('job_submitter_id_foreign' /*tableName_columnName_foreign*/);
/*repeat for as many keys as you added to this table*/
});
Repeat this for as many tables as you added foreign keys too, until you have dropped all foreign keys that you added.
Once you have made all the tables and keys you desire, return to the terminal and migrate them to your database.
php artisan migrate