How do i add a colum to my database table without losing my Database Entrys
Hello,
I implemented a Laravel Application with a database.
I have a table named cars with 150 entrys.
i'd like to add a column named seats and set it to 5 for every car, and would change the cars with 9 seats to that number manually later.
What would be the best way to add this column without deleting all my entrys?
If you have a migration that adds one column with a default value, it won't delete the other entries in the database. One important thing is that you set a default value for that column or make it nullable! So your migration will look like this:
public function up()
{
Schema::table('cars', function (Blueprint $table) {
$table->integer('seats')->default(5);
});
}
So you need to create a new migration using php artisan make:migration add_seats_cars_table to be clear! If you run php artisan migrate the column will be added without losing any data ;)
Something like this would do the trick:
Depending on your requirements you could set your amount of seats to default null (nullable, when you don't know) or to an integer like 5.
Schema::table('cars', function (Blueprint $table) {
$table->integer('seats')->nullable()->after('some_other_field');
});
DB::query('UPDATE cars SET seats = 5 WHERE seats IS NULL');
@lxg please select the answer that helped you as correct one so that person gets the points they've earned and so others will easier see that the problem is solved and if anyone has the same issue they will know right away what helped you. Thanks.
@click Some people update the initial migrations and therefore they lose all there data because they need to remigrate the whole database. Not everyone is known with this approach ;)