猿问

从 json 文件播种拉拉维尔应用时插入空值

在我的 laravel 应用程序中,我有一个 json 文件,我用它来将一些产品播种到我的数据库中。出于某种原因,当我尝试保存产品时,我正在为标题和productcategory_id字段插入空值,即使认为数组值在那里,json也会转换为具有json_decode的数组。


这是我的逻辑:


<?php

use Illuminate\Database\Seeder;

use App\Models\Product;



class ProductsSeeder extends Seeder

{



    public function run()

    {

        $json = File::get(base_path().'/json/Products.json');


        $products = json_decode($json, true);


        var_dump($products);


        foreach ($products as $product)

        {

            echo($product['title']);

            echo($product['productcategory_id']);

            $product = new Product();

            $product->title = $product['title'];

            $product->productcategory_id = $product['productcategory_id'];

            $product->save();

        }

    }

}

我的 json 文件摘录:


[

    { "productcategory_id" : 1, "title":"Hamb.Ternera Maxi"},

    { "productcategory_id" : 1, "title":"Hamb. Ternera Doble"}, 

    { "productcategory_id" : 1, "title":"Hamb. Pollo"}, 

    { "productcategory_id" : 1, "title":"Hamb. Mini"}, 

    { "productcategory_id" : 1, "title":"Camp. clásico"}, 

    { "productcategory_id" : 1, "title":"Camp. ternera"}, 

]

正如你所看到的,我使用var_dump来查看json数据是否正确转换为php assoc数组,bt我仍然收到错误。我的 shell 中的完整错误消息是:


   Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `products` (`title`, `productcategory_id`, `updated_at`, `created_at`) values (, , 2020-02-16 20:25:51, 2020-02-16 20:25:51))



烙印99
浏览 101回答 1
1回答

繁星淼淼

问题可能是您正在使用相同的变量来循环并获取值。试试像这样:foreach ($products as $product)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo($product['title']);&nbsp; &nbsp; &nbsp; &nbsp; echo($product['productcategory_id']);&nbsp; &nbsp; &nbsp; &nbsp; $product_n = new Product();&nbsp; &nbsp; &nbsp; &nbsp; $product_n->title = $product['title'];&nbsp; &nbsp; &nbsp; &nbsp; $product_n->productcategory_id = $product['productcategory_id'];&nbsp; &nbsp; &nbsp; &nbsp; $product_n->save();&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答