如何在循环迁移中使用计数器table? (laravel 5.3)

How to using counter in loop 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()
    {
        $i=1;
        Akun::all()->each(function($akun) { 
            $masterLookup = new Master_lookup; 
            $masterLookup->id           = $i;
            $masterLookup->parent_id    = NULL;
            $masterLookup->code         = $akun->kdakun;
            $masterLookup->name         = $akun->nmakun;
            $masterLookup->type         = 'akun';
            $masterLookup->information  = json_encode($akun->kdjenbel);
            $masterLookup->save();
            $i++;
        });
    }
}

执行时存在错误: undefined variable: i

有没有人可以帮助我?

使用匿名函数时,必须将任何此类变量传递给使用语言结构。 你能试试这个吗:

Akun::all()->each(function($akun) use ($i) { 
        $masterLookup = new Master_lookup; 
        $masterLookup->id           = $i;
        $masterLookup->parent_id    = NULL;
        $masterLookup->code         = $akun->kdakun;
        $masterLookup->name         = $akun->nmakun;
        $masterLookup->type         = 'akun';
        $masterLookup->information  = json_encode($akun->kdjenbel);
        $masterLookup->save();
        $i++;
    });

尝试以下方法之一: 创建 class 变量并使用它:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Akun;
use App\Models\Master_lookup;

class MasterLookupsTableSeeder extends Seeder
{
    public $i;
    public function run()
    {
        $this->i = 1;
        Akun::all()->each(function($akun) { 
            $masterLookup = new Master_lookup; 
            $masterLookup->id           = $this->i;
            $masterLookup->parent_id    = NULL;
            $masterLookup->code         = $akun->kdakun;
            $masterLookup->name         = $akun->nmakun;
            $masterLookup->type         = 'akun';
            $masterLookup->information  = json_encode($akun->kdjenbel);
            $masterLookup->save();
            $this->i++;
        });
    }
}

根据我的意见,class 变量是处理此问题的方法。