Laravel 5.1种子填充新列

5

我有一个叫做locations的数据库表,需要添加一个新的status列。我设置了以下迁移文件,当我运行php artisan migrate时,可以成功添加字段,但是如何为表中的每一行插入值Active呢?

<?php

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

class AddStatusToLocationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('locations', function(Blueprint $table)
        {
            $table->string('status')->after('email');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('locations', function(Blueprint $table)
        {
            $table->dropColumn('status');
        });
    }
}
3个回答

3

您可以将字段设置为默认值

$table->string('status')->after('email')->default('active')

如果您只需要更新当前的记录,可以使用seeding进行操作:
运行以下Artisan命令:
php artisan make:seeder AddStatusSeeder    

然后在你的AddStatusSeeder文件中:

<?php

use Illuminate\Database\Seeder;

class AddStatusSeeder extends Seeder
{
     /**
     * Run the database seeds.
     *
     * @return void
     */
     public function run()
     {
         DB::table('locations')->update([
            'status' => 'Active'
         ]);
     }
 }

谢谢以上内容。有没有关于如何在需要唯一ID时修改上述代码的想法?目前,当我生成UUID时,相同的ID会用相同的值填充每一行。 代码:'public_id' => (string)Uuid::generate(4) - ejntaylor
DB::table('your-table')->update([...])没有where条件,意味着它将更新所有记录。您需要循环遍历所有行并逐个更新UUID。 - Iamzozo

1
你有两种解决方案
你可以在现有的seeder中添加一个值到这个表里
你也可以创建一个新的seeder,在其中获取每个位置,添加你的新字段值,并像下面这样保存
foreach(Location::all() as $location){
    $location->status = 'Active';
    $location->save();
}

0

你需要使用数据库填充。你可以为locations表创建一个模型,或者使用DB::table的方式进行插入。

然后你可以运行php artisan migrate --seed来创建架构并填充数据库。


1
是的,我已经有了一个位置表的模型和一个种子文件。但我的问题是,如何播种一个新的列? - V4n1ll4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接