Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

php - Update table and add data in a Laravel 5 Migration

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.

I have the table 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);
});

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.

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

  • Can I use Seeds in Laravel 5 to update values or I can just insert them?
  • Can I create some SQL inside the Seeds (or migrations) to do this update for me?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...