Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter a Column with migration file?

Using orchad 1.6 in the migration file I have just altered a table and added a column. I need this column to be NotNull, but it doesnt allow you to alter a table enter a NotNull type, so i've used Nullable and entered data into the existing columns.

I then want to edit this column and change it to a Nullable, but am unsure how....

public int UpdateFrom37()
        {
            SchemaBuilder.AlterTable("ManufacturedProductOrders", table => table
                .AddColumn<DateTime>("DateOrdered", c => c.Nullable())
                );

            return 38;
        }

        public int UpdateFrom38()
        {
            SchemaBuilder.AlterTable("ManufacturedProductOrders", table => table
                .AlterColumn("DateOrdered", c => c.WithType(dbType.???????????
                );
        }
like image 276
John Avatar asked Sep 19 '13 11:09

John


People also ask

How do I add a column to an existing migration without losing data?

Make sure that when you are adding new column in your table, that column should be nullable, and should not be unique. Otherwise you will face error. Because when a new column is created it will be empty(not unique). In that condition you have to rollback the migration.

How do I change the datatype in migration?

open your migration file and write down below. Schema::table('yourTable', function (Blueprint $table) { $table->string('column_name','4294967295')->change(); }); As, longText have maximum of 4,294,967,295 character limit, Laravel will automatically change column_name to longText data type.

How do I add a column to an existing table in Laravel migration?

The Laravel migrations will use the Schema facade to create and modify database tables and columns: Schema::create('tasks', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); Inside the facade, you could specify the different columns that you want to add.


1 Answers

I guess you want to change from NULL to NOT NULL, right? The code above clearly states that you already have a nullable column.

AlterColumn command does not currently allow changing column 'nullability'.

Your best option is to issue a manual ALTER TABLE command through SchemaBuilder.ExecuteSql() or directly in the database. You can read about it eg. here.

like image 62
Piotr Szmyd Avatar answered Sep 20 '22 04:09

Piotr Szmyd