如何在 foreach 迁移中使用计数器 table? (laravel 5.3)
How to using counter in foreach migration table? (laravel 5.3)
我的代码是这样的:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Akun;
use App\Models\Master_lookup;
class MasterLookupsTableSeeder extends Seeder
{
public function run()
{
foreach (Akun::all() as $key => $value) {
$masterLookup = new Master_lookup;
$masterLookup->id = ++$key
$masterLookup->parent_id = NULL;
$masterLookup->code = $value->kdakun;
$masterLookup->name = $value->nmakun;
$masterLookup->type = 'akun';
$masterLookup->information = json_encode($value->kdjenbel);
$masterLookup->save();
}
}
}
我用索引$key
来对抗
但是执行时出现错误:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected '$masterLookup' (T_VARIABLE)
有没有人可以帮助我?
不要手动添加 id
。 ID 应该是 AUTO INCREMENT
,这样 DB 可以自动增加它。 id
在迁移中应该这样定义:
$table->increments('id');
更新
如果您出于某种原因不想使用 increments()
,只需使用这个:
$masterLookup->id = $key;
这应该可行,因为您正在遍历 Eloquent 集合,所以 key
是唯一的。
在您的代码中,您没有在行尾添加半列。
$masterLookup->id = ++$key;
在行尾使用分号 (;)。
我的代码是这样的:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Akun;
use App\Models\Master_lookup;
class MasterLookupsTableSeeder extends Seeder
{
public function run()
{
foreach (Akun::all() as $key => $value) {
$masterLookup = new Master_lookup;
$masterLookup->id = ++$key
$masterLookup->parent_id = NULL;
$masterLookup->code = $value->kdakun;
$masterLookup->name = $value->nmakun;
$masterLookup->type = 'akun';
$masterLookup->information = json_encode($value->kdjenbel);
$masterLookup->save();
}
}
}
我用索引$key
来对抗
但是执行时出现错误:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected '$masterLookup' (T_VARIABLE)
有没有人可以帮助我?
不要手动添加 id
。 ID 应该是 AUTO INCREMENT
,这样 DB 可以自动增加它。 id
在迁移中应该这样定义:
$table->increments('id');
更新
如果您出于某种原因不想使用 increments()
,只需使用这个:
$masterLookup->id = $key;
这应该可行,因为您正在遍历 Eloquent 集合,所以 key
是唯一的。
在您的代码中,您没有在行尾添加半列。
$masterLookup->id = ++$key;
在行尾使用分号 (;)。