【问题标题】:Laravel5 Using JSON & Seeder to feed databaseLaravel5 使用 JSON 和 Seeder 提供数据库
【发布时间】:2017-08-20 14:35:11
【问题描述】:

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

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

这是我的代码。

<?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->toArray(); 并直接使用 $data。

任何帮助表示赞赏。

【问题讨论】:

  • 我能知道,你把你的 json 文件放在哪里了吗?我无法播种我的 json 数据

标签: php json database laravel


【解决方案1】:

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

$data = json_decode($json, true);

来自文档:

关联

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

http://php.net/json_decode

【讨论】:

    【解决方案2】:

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

    $array1 = (array) $data;
    

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多