【问题标题】:How to using counter in loop migration table? (laravel 5.3)如何在循环迁移表中使用计数器? (laravel 5.3)
【发布时间】:2016-12-28 06:15:09
【问题描述】:

我的代码是这样的:

<?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 laravel migration laravel-5.3


    【解决方案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++;
            });
        }
    }
    

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

    【讨论】:

    • 谢谢。第一种方法,它奏效了。但是,第二种方法不起作用
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 2017-05-07
      • 2018-11-21
      相关资源
      最近更新 更多