我的代码是这样的:
<?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++;
});
}
}
执行时,存在错误:未定义变量:i
有没有人可以帮助我?
答案 0 :(得分:1)
尝试下面给出的一个: 创建类变量并使用它:
<?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++;
});
}
}
根据我的观点,类变量是解决这个问题的方法。
答案 1 :(得分:0)
使用匿名函数时,必须将任何此类变量传递给use语言构造。 你能试试这个:
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++;
});