微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 更新表并在Laravel 5 Migration中添加数据

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

我有权证表:

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

所以我使用新的迁移文件创建了新字段:

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

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

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

我花了几个小时寻找一些方法来使用种子,但我没有找到.所以基本上我有两个问题:

>我可以在Laravel 5中使用Seeds来更新值,还是可以插入它们?
>我可以在Seeds(或迁移)中创建一些sql来为我做这个更新吗?

解决方法:

基于此链接,我找到了答案: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++;
    }

无论如何,谢谢你的帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐