Laravel5使用JSON&播种机供给数据库

时间:2017-03-27 18:34:20

标签: php json database laravel

我尝试使用laravel的有用种子功能来使用自定义数据填充表格。而不是使用Seeder的Faker Im。因此我创建了一个:

  1. '/ json /'文件夹并将我的JSON数据文件放在那里。
  2. 最后,在播种器中,我将数据映射到JSON对象属性。
  3. 这是我的代码。

    <?php
    use Illuminate\Database\Seeder;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Http\Request;
    
    class JsonTableSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            $json = File::get("/json/cell-1.json");
            $data = json_decode($json);
            $array1 = $data->toArray();
            foreach ($array1['products'] as $obj) {
                DB::table('products')->insert(array(
                    'id' => $obj->id,
                    'name' => $obj->productName,
                    'sku' => $obj->productSku
                ));
                foreach ($data['relatedProducts'] as $obj) {
                    DB::table('products_related')->insert(array(
                        'sku' => $obj->sku
                    ));
                }
            }
        }
    }
    

    但我收到许多不同的错误,例如:

    • 调用未定义的方法stdClass :: toArray()

    • 不能使用stdClass类型的对象作为数组(如果我不使用$ array1 = $ data-&gt; toArray();并直接使用$ data。

    任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

默认情况下,

json_decode将返回一个对象。如果您想使用数组,只需使用$assoc = true

$data = json_decode($json, true);

来自文档:

  

<强> ASSOC

     

当为TRUE时,返回的对象将被转换为关联数组。

https://cloud.google.com/container-engine/docs/node-taints

答案 1 :(得分:1)

$ data是一个普通的对象而不是laravel集合,因此它没有toArray。您可以通过执行以下操作将对象类型转换为数组

ehayllo worwaylday.