首页 > 解决方案 > Laravel:无法使用 Foreach 创建多个数据关系

问题描述

我在创建数据时遇到问题,数据返回 null 和错误。Maatwebsite/excel‍‍‍</code> import. In my import class, I want to create data with the relation, when I try the dd variable that contains child data its works just fine, but when I ‍<code>saveMany()

完整性约束违规:1048 列“描述”不能为空

这是我的代码:

public function collection(Collection $rows) {
    $parent = Parent::create([
        'name' => $this->name,
        'slug' => $this->slug,
        'month' => $this->month,
    ]);

    foreach ($rows as $row) {
        $item = new Child([
            'description' => $row['description'],
            'status' => $row['status'],
        ]);
        $items[] = $item;
    }
    $parent->childs()->saveMany($items);
}

标签: phplaraveleloquentlaravel-excel

解决方案


可能你在 foreach 中的 $row['description'] 有空值。

像这样编辑你的循环代码

 foreach ($rows as $row) {
        if(!empty($row['description]))
        {
          $item = new Child([
            'description' => $row['description'],
            'status' => $row['status'],
          ]);
         $items[] = $item;
        }
    }

并编辑最后一行

if(!empty($items))
  $parent->childs()->saveMany($items);

推荐阅读