Php 如何在循环迁移表中使用计数器?(拉威尔5.3)

Php 如何在循环迁移表中使用计数器?(拉威尔5.3),php,laravel,migration,laravel-5.3,Php,Laravel,Migration,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::

我的代码如下:

<?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++;
        });
    }
}

使用匿名函数时,任何此类变量都必须传递给use language构造。
你能试试这个吗

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++;
    });

请尝试以下给定选项之一: 创建类变量并使用它:

<?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++;
        });
    }
}

谢谢。第一种方式,它起作用了。但是,第二种方法不起作用