简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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