为什么不保存到数据库?

时间:2019-09-19 14:59:49

标签: php sql database laravel

我正在尝试将新产品保存到数据库中,该产品具有我也在尝试保存的出口因素,为什么这不起作用?

 if ($request->has('export_factors')) {
    $exportationFactors = [];

    foreach ($request->get('export_factors') as $item) {
        if (key_exists('country_id', $item)) {
            $export = ExportationFactor::where('country_id', $item['country_id'])->first();
        } else if (key_exists('fi', $item)) {
            $export = ExportationFactor::where('fi', $item['fi'])->first();
        } else if (key_exists('margin', $item)) {
            $export = ExportationFactor::where('margin', $item['margin'])->first();
        }

        $export->save();

        $exportationFactors[] = [
            "product_id" => $export->product_id,
             "country_id" => $export->country_id,
             "fi" => $export->fi,
             "margin" => $export->margin
        ];

        if (count($exportationFactors) > 0) {
            ExportationFactor::insert($exportationFactors);
        }

    }
}

我遇到的错误是:

  

在null上调用成员函数save()

$export->save();

2 个答案:

答案 0 :(得分:1)

在未设置$export的情况下(如果与任何key_exists()测试都不匹配的话),代码中可能会有一条路径。

这是一个错误,应该将其设置为某些值-或者您应该在保存之前检查它是否已设置...

// Check if export is needed
if ( !empty($export) )  {
    $export->save();

    $exportationFactors[] = [
        "product_id" => $export->product_id,
         "country_id" => $export->country_id,
         "fi" => $export->fi,
         "margin" => $export->margin
    ];

    if (count($exportationFactors) > 0) {
        ExportationFactor::insert($exportationFactors);
    }
}

您还应该确保每次在循环中重置该值,因为它可能具有上一个循环中遗留下来的值...

foreach ($request->get('export_factors') as $item) {
    unset($export);

答案 1 :(得分:1)

将插入内容放在循环之外以提高性能,不要对不存在的内容进行保存

$product_id = //you need to fill this one.
if ($request->has('export_factors')) {
    $exportationFactors = [];

    foreach ($request->get('export_factors') as $item) {
        $country_id = $item['country_id']??null;
        $fi = $item['fi']??null;
        $margin = $item['margin']??null;
        if (isset($fi, $margin, $country_id) {
            $exportationFactors[] = [
                "product_id" => $product_id,
                "country_id" => $country_id,
                "fi" => $fi,
                "margin" => $margin,
            ];
        }
    }
    if (count($exportationFactors)) {
        ExportationFactor::insert($exportationFactors);
    }
}
相关问题