简体   繁体   中英

How to alter the column in laravel?

I am using laravel and mysql database ,i want to change the column type and data what ever present inside the database can you please help me to acheive this one..

Schema::table('users', function (Blueprint $table) {

// DB::query("ALTER TABLE `users`.`percentage` CHANGE COLUMN `percentage/100` Decimal(23,4) NUllable ;");

$table->decimal('percentage')->storedAs("'percentage' / 100");

});

Question: Updating table schema without affecting data in Laravel

For example this is your database migrate file:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

    public function up()
    {
        Schema::create('users', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('percentage');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('users');
    }

}

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class changeColumnUsersTable extends Migration {

    public function up()
    {
        Schema::table('users', function($table)
        {
            $table->decimal('percentage', 23, 4)->change();
        });

    }

    public function down()
    {
        Schema::table('users', function($table)
        {
            $table->decimal('percentage', 23, 4)->change();
        });
    }

}

Then migrate using the command,

php artisan migrate

In the Laravel Documentation, there's a Updating Column Attributes

But the thing is ->change() doesn't work with storeAs , so you may want to use a raw query here:

public function up()
{
    DB::statement("ALTER TABLE `users` CHANGE `percentage` `percentage` DECIMAL(23,4) AS (('percentage' / 100)) STORED");
}

这是 Laravel 关于这个问题的官方文档: 更新列属性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM