加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-07-06 05:19:55 所属栏目:大数据 来源: https://www.jb51.cc
导读:我需要在我的laravel项目中添加一个新列,没问题,我使用Schema :: table()来更新它没关系. 现在我需要找出我在这个表上有多少记录并更新一些值. 我有权证表: Schema::create('warrant_grants', function(Blueprint $table) { $table-increments('id'); $tabl

我需要在我的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++;
    }

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

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读