Ramon Royo
Ramon Royo

Reputation: 165

Laravel migrations on SQL Server use the data type NCHAR, how can I force it to use CHAR instead?

I've created a very simple migration, that creates a table with a FK referencing a column on an existing table. The problem is that the migration creates a NCHAR datatype column, while the referenced column is of CHAR datatype, so the FK can't be created because of different datatypes columns.

Is there any way to enforce Laravel to use CHAR instead of NCHAR?

Thanks!

Upvotes: 2

Views: 996

Answers (1)

Ramon Royo
Ramon Royo

Reputation: 165

I've got a work around for this issue, I got the idea from mikebronner's comment here https://github.com/laravel/framework/issues/9636.

I've modified my migration to alter the 'cliente' column type, after it's been created, using raw SQL. This way I can override Laravel's default datatype of NCHAR, when creating CHAR columns. The altered column can't have any restrictions such as FK or PK before being modified. Hope this helps anyone else having this problem in the future.

The following code is inside my migration file, right after the code that creates the table itself, inside the up() function.

    Schema::table('UsuariosWeb', function ($table) {
        DB::statement("
            ALTER TABLE UsuariosWeb ALTER COLUMN cliente CHAR(6) NOT NULL;
        ");

        $table->primary('cliente');
        $table->foreign('cliente')->references('Cliente')->on('Clientes');
    });

Upvotes: 3

Related Questions