2016-12-28 80 views
3

我的代碼是這樣的:如何在循環遷移表中使用計數器? (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++; 
     }); 
    } 
} 

執行時,有存在錯誤:未定義的變量:我

是否有任何人誰可以幫幫我嗎?

回答

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

基於

我看來,類變量是有辦法對付這個。

+0

謝謝。第一種方式,它的工作。但是,第二種方式不起作用 –

0

使用匿名函數時,必須將任何此類變量傳遞給使用語言結構。 你可以試試這個:

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