简体   繁体   English

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

[英]How to using counter in loop migration table? (laravel 5.3)

My code is like this : 我的代码是这样的:

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

When executed, there is exist error : undefined variable: i 执行时,存在错误:未定义变量:i

Is there any people who can help me? 有没有人可以帮助我?

Try one of the given below: Create class variable and use it: 尝试下面给出的一个:创建类变量并使用它:

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

Based my opinion, class variable is be way to dealing with this. 根据我的观点,类变量是解决这个问题的方法。

Any such variables must be passed to the use language construct when using anonymous functions. 使用匿名函数时,必须将任何此类变量传递给use语言构造。 Can you try this one: 你能试试这个:

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