在Laravel 5迁移中更新表并添加数据 [英] Update table and add data in a Laravel 5 Migration

查看:226
本文介绍了在Laravel 5迁移中更新表并添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在laravel项目中添加一个新列,对此没有问题,我使用Schema::table()进行更新,没关系. 现在,我需要找出该表上有多少条记录,并用一些值进行更新.

I need to add a new column in my laravel Project, no problem for this, I used the Schema::table() to update and it's ok. Now I need to find out how many records I have on this table and update with some value.

我有桌子Warrants:

Schema::create('warrant_grants', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('warrant_plan_id');
    $table->integer('shareholder_id');
});

因此,我使用新的迁移文件创建了新字段:

So I created the new field with a new migration file:

Schema::table('warrant_grants',function ($table) {
    $table->string('name',100);
});

现在,我需要使用一些值更新表中的该字段name,例如,如果该表具有100条记录,那么我需要在每一行中插入值"Warrant-X",其中X是一个以数字开头的数字1到100. 例如:

Now I need to update this field name in the table with some values, for example if the table has 100 records, then I need to insert in every row the value "Warrant-X" where X is a number starting with 1 to 100. For example:

Warrant-1,Warrant-2,.... Warrant-100.

Warrant-1, Warrant-2, ....Warrant-100.

我花了数小时寻找使用Seeds进行此操作的方法,但没有找到.所以基本上我有两个问题:

I spent hours looking for some way to do this using Seeds but I didn't found. So basically i have two questions:

  • 我可以在Laravel 5中使用种子"来更新值,还是可以只插入它们?
  • 我可以在种子(或迁移)中创建一些SQL来为我执行此更新吗?

推荐答案

基于此链接,我找到了答案: https://stackoverflow.com/a/23506744/4650792

Based on this link i found the answer: https://stackoverflow.com/a/23506744/4650792

Schema::table('warrant_grants',function ($table){
        $table->string('name',100)->after('id')->nullable();
    });

    $results = DB::table('warrant_grants')->select('id','name')->get();

    $i = 1;
    foreach ($results as $result){
        DB::table('warrant_grants')
            ->where('id',$result->id)
            ->update([
                "name" => "Warrant-".$i
        ]);
        $i++;
    }

无论如何,谢谢大家的帮助.

Thanks for the help anyway guys.

这篇关于在Laravel 5迁移中更新表并添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆