繁体   English   中英

如何在循环迁移表中使用计数器? (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++;
        });
    }
}

执行时,存在错误:未定义变量: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++;
        });
    }
}

根据我的观点,类变量是解决这个问题的方法。

使用匿名函数时,必须将任何此类变量传递给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++;
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM