我需要在我的 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);
});
现在我需要用一些值更新表中的字段 name
,例如,如果表有 100 条记录,那么我需要在每一行中插入值“Warrant-X”,其中X 是以 1 到 100 开头的数字。
例如:
Warrant-1, Warrant-2, ....Warrant-100.
我花了几个小时寻找使用 Seeds 执行此操作的方法,但没有找到。所以基本上我有两个问题:
- 我可以在 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++;
}
谢谢大家的帮助。
关于php - 在 Laravel 5 迁移中更新表并添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37478526/